code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
''' a helper function shared between functions that will return a
container_id. First preference goes to a container_id provided by
the user at runtime. Second preference goes to the container_id
instantiated with the client.
Parameters
==========
... | def get_container_id(self, container_id=None) | a helper function shared between functions that will return a
container_id. First preference goes to a container_id provided by
the user at runtime. Second preference goes to the container_id
instantiated with the client.
Parameters
==========
co... | 8.936507 | 3.133983 | 2.851485 |
''' Run a command, show the message to the user if quiet isn't set,
and return the return code. This is a wrapper for the OCI client
to run a command and easily return the return code value (what
the user is ultimately interested in).
Parameters
=====... | def _run_and_return(self, cmd, sudo=None) | Run a command, show the message to the user if quiet isn't set,
and return the return code. This is a wrapper for the OCI client
to run a command and easily return the return code value (what
the user is ultimately interested in).
Parameters
==========
... | 7.839124 | 3.180142 | 2.465023 |
''' a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)
not implemented yet.
... | def _init_command(self, action, flags=None) | a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)
not implemented yet. | 9.369371 | 2.692235 | 3.480146 |
'''export will export an image, sudo must be used.
Parameters
==========
image_path: full path to image
tmptar: if defined, use custom temporary path for tar export
'''
from spython.utils import check_install
check_install()
if tmptar is None:
tmptar = "/%s... | def export(self, image_path, tmptar=None) | export will export an image, sudo must be used.
Parameters
==========
image_path: full path to image
tmptar: if defined, use custom temporary path for tar export | 7.667802 | 3.734135 | 2.053434 |
'''write_json will (optionally,pretty print) a json object to file
:param json_obj: the dict to print to json
:param filename: the output file to write to
:param pretty_print: if True, will use nicer formatting
'''
with open(filename, mode) as filey:
if print_pretty:
filey.wr... | def write_json(json_obj, filename, mode="w", print_pretty=True) | write_json will (optionally,pretty print) a json object to file
:param json_obj: the dict to print to json
:param filename: the output file to write to
:param pretty_print: if True, will use nicer formatting | 3.215125 | 1.975744 | 1.627298 |
''' execute: send a command to a container
Parameters
==========
image: full path to singularity image
command: command to send to container
app: if not None, execute a command in context of an app
writable: This option makes the file system accessible as read/... | def execute(self,
image = None,
command = None,
app = None,
writable = False,
contain = False,
bind = None,
stream = False,
nv = False,
return_result=False) | execute: send a command to a container
Parameters
==========
image: full path to singularity image
command: command to send to container
app: if not None, execute a command in context of an app
writable: This option makes the file system accessible as read/write
... | 6.195061 | 3.133312 | 1.977161 |
'''parse a table to json from a string, where a header is expected by default.
Return a jsonified table.
Parameters
==========
table_string: the string table, ideally with a header
header: header of expected table, must match dimension (number columns)
remove_rows: an inte... | def parse_table(table_string, header, remove_rows=1) | parse a table to json from a string, where a header is expected by default.
Return a jsonified table.
Parameters
==========
table_string: the string table, ideally with a header
header: header of expected table, must match dimension (number columns)
remove_rows: an integer to ... | 6.102181 | 2.354091 | 2.592161 |
'''get is a list for a single instance. It is assumed to be running,
and we need to look up the PID, etc.
'''
from spython.utils import check_install
check_install()
# Ensure compatible for singularity prior to 3.0, and after 3.0
subgroup = "instance.list"
if 'version 3' in self.ver... | def get(self, name, return_json=False, quiet=False) | get is a list for a single instance. It is assumed to be running,
and we need to look up the PID, etc. | 6.866303 | 5.484925 | 1.25185 |
'''determine the message level in the environment to set based on args.
'''
level = "INFO"
if args.debug is True:
level = "DEBUG"
elif args.quiet is True:
level = "QUIET"
os.environ['MESSAGELEVEL'] = level
os.putenv('MESSAGELEVEL', level)
os.environ['SINGULARITY_MESSAGE... | def set_verbosity(args) | determine the message level in the environment to set based on args. | 5.633942 | 4.432431 | 1.271073 |
''' The Image client holds the Singularity image command group, mainly
deprecated commands (image.import) and additional command helpers
that are commonly use but not provided by Singularity
The levels of verbosity (debug and quiet) are passed from the main
client via the environmen... | def generate_image_commands() | The Image client holds the Singularity image command group, mainly
deprecated commands (image.import) and additional command helpers
that are commonly use but not provided by Singularity
The levels of verbosity (debug and quiet) are passed from the main
client via the environment variab... | 9.687146 | 2.620328 | 3.696921 |
'''return the initial Singularity command with any added flags.
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)
not implemented yet.
'''
if not isinstance(action, list):
act... | def init_command(self, action, flags=None) | return the initial Singularity command with any added flags.
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)
not implemented yet. | 6.355158 | 2.364658 | 2.68756 |
'''generate bind string will take a single string or list of binds, and
return a list that can be added to an exec or run command. For example,
the following map as follows:
['/host:/container', '/both'] --> ["--bind", "/host:/container","--bind","/both" ]
['/both'] --... | def generate_bind_list(self, bindlist=None) | generate bind string will take a single string or list of binds, and
return a list that can be added to an exec or run command. For example,
the following map as follows:
['/host:/container', '/both'] --> ["--bind", "/host:/container","--bind","/both" ]
['/both'] --> ["--b... | 6.330265 | 2.277025 | 2.78006 |
'''send command is a non interactive version of run_command, meaning
that we execute the command and return the return value, but don't
attempt to stream any content (text from the screen) back to the
user. This is useful for commands interacting with OCI bundles.
Parameters
====... | def send_command(self, cmd, sudo=False, stderr=None, stdout=None) | send command is a non interactive version of run_command, meaning
that we execute the command and return the return value, but don't
attempt to stream any content (text from the screen) back to the
user. This is useful for commands interacting with OCI bundles.
Parameters
==========
... | 9.210214 | 1.807492 | 5.095576 |
'''run_command is a wrapper for the global run_command, checking first
for sudo and exiting on error if needed. The message is returned as
a list of lines for the calling function to parse, and stdout uses
the parent process so it appears for the user.
Parameters
==========
... | def run_command(self, cmd,
sudo=False,
capture=True,
quiet=None,
return_result=False) | run_command is a wrapper for the global run_command, checking first
for sudo and exiting on error if needed. The message is returned as
a list of lines for the calling function to parse, and stdout uses
the parent process so it appears for the user.
Parameters
==========
cmd: ... | 6.616894 | 2.327226 | 2.843253 |
'''load a recipe file into the client, first performing checks, and
then parsing the file.
Parameters
==========
recipe: the original recipe file, parsed by the subclass either
DockerRecipe or SingularityRecipe
'''
self.recipe = recip... | def load(self, recipe) | load a recipe file into the client, first performing checks, and
then parsing the file.
Parameters
==========
recipe: the original recipe file, parsed by the subclass either
DockerRecipe or SingularityRecipe | 17.182291 | 4.027985 | 4.265729 |
'''basic sanity checks for the file name (and others if needed) before
attempting parsing.
'''
if self.recipe is not None:
# Does the recipe provided exist?
if not os.path.exists(self.recipe):
bot.error("Cannot find %s, is the path correct?" %s... | def _run_checks(self) | basic sanity checks for the file name (and others if needed) before
attempting parsing. | 9.420236 | 4.715009 | 1.997925 |
'''parse is the base function for parsing the recipe, whether it be
a Dockerfile or Singularity recipe. The recipe is read in as lines,
and saved to a list if needed for the future. If the client has
it, the recipe type specific _parse function is called.
Instruction... | def parse(self) | parse is the base function for parsing the recipe, whether it be
a Dockerfile or Singularity recipe. The recipe is read in as lines,
and saved to a list if needed for the future. If the client has
it, the recipe type specific _parse function is called.
Instructions for makin... | 9.387969 | 2.126083 | 4.415617 |
'''save will convert a recipe to a specified format (defaults to the
opposite of the recipe type originally loaded, (e.g., docker-->
singularity and singularity-->docker) and write to an output file,
if specified. If not specified, a temporary file is used.
Paramete... | def save(self, output_file=None,
convert_to=None,
runscript="/bin/bash",
force=False) | save will convert a recipe to a specified format (defaults to the
opposite of the recipe type originally loaded, (e.g., docker-->
singularity and singularity-->docker) and write to an output file,
if specified. If not specified, a temporary file is used.
Parameters
... | 7.825387 | 1.862441 | 4.201682 |
'''This is a convenience function for the user to easily call to get
the most likely desired result, conversion to the opposite format.
We choose the selection based on the recipe name - meaning that we
perform conversion with default based on recipe name. If the recipe
... | def convert(self, convert_to=None,
runscript="/bin/bash",
force=False) | This is a convenience function for the user to easily call to get
the most likely desired result, conversion to the opposite format.
We choose the selection based on the recipe name - meaning that we
perform conversion with default based on recipe name. If the recipe
object i... | 11.006838 | 1.34457 | 8.186142 |
'''see convert and save. This is a helper function that returns
the proper conversion function, but doesn't call it. We do this
so that in the case of convert, we do the conversion and return
a string. In the case of save, we save the recipe to file for the
user.
... | def _get_converter(self, convert_to=None) | see convert and save. This is a helper function that returns
the proper conversion function, but doesn't call it. We do this
so that in the case of convert, we do the conversion and return
a string. In the case of save, we save the recipe to file for the
user.
P... | 10.804603 | 1.999923 | 5.402511 |
'''a helper function to return a conversion temporary output file
based on kind of conversion
Parameters
==========
convert_to: a string either docker or singularity, if a different
'''
conversion = self._get_conversion_type(convert_to)
prefi... | def _get_conversion_outfile(self, convert_to=None) | a helper function to return a conversion temporary output file
based on kind of conversion
Parameters
==========
convert_to: a string either docker or singularity, if a different | 8.571394 | 3.527211 | 2.430077 |
'''a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None)
'''
acceptable = ['singularity', 'docker']
# Default is to ... | def _get_conversion_type(self, convert_to=None) | a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None) | 8.084306 | 3.621956 | 2.232028 |
'''write a script with some lines content to path in the image. This
is done by way of adding echo statements to the install section.
Parameters
==========
path: the path to the file to write
lines: the lines to echo to the file
chmod: If true, ... | def _write_script(path, lines, chmod=True) | write a script with some lines content to path in the image. This
is done by way of adding echo statements to the install section.
Parameters
==========
path: the path to the file to write
lines: the lines to echo to the file
chmod: If true, change perm... | 6.952014 | 2.36304 | 2.941978 |
''' get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
Parameters
==========
container_id: th... | def state(self, container_id=None, sudo=None, sync_socket=None) | get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
Parameters
==========
container_id: the id to g... | 6.00534 | 1.989121 | 3.019093 |
''' A generic state command to wrap pause, resume, kill, etc., where the
only difference is the command. This function will be unwrapped if the
child functions get more complicated (with additional arguments).
Equivalent command line example:
singularity oci <command> <con... | def _state_command(self, container_id=None, command='start', sudo=None) | A generic state command to wrap pause, resume, kill, etc., where the
only difference is the command. This function will be unwrapped if the
child functions get more complicated (with additional arguments).
Equivalent command line example:
singularity oci <command> <container_ID... | 8.520568 | 1.835788 | 4.641368 |
''' stop (kill) a started OciImage container, if it exists
Equivalent command line example:
singularity oci kill <container_ID>
Parameters
==========
container_id: the id to stop.
signal: signal sent to the container (default SIGTERM)
su... | def kill(self, container_id=None, sudo=None, signal=None) | stop (kill) a started OciImage container, if it exists
Equivalent command line example:
singularity oci kill <container_ID>
Parameters
==========
container_id: the id to stop.
signal: signal sent to the container (default SIGTERM)
sudo: Add s... | 6.846856 | 2.272945 | 3.012328 |
''' resume a stopped OciImage container, if it exists
Equivalent command line example:
singularity oci resume <container_ID>
Parameters
==========
container_id: the id to stop.
sudo: Add sudo to the command. If the container was created by root,
... | def resume(self, container_id=None, sudo=None) | resume a stopped OciImage container, if it exists
Equivalent command line example:
singularity oci resume <container_ID>
Parameters
==========
container_id: the id to stop.
sudo: Add sudo to the command. If the container was created by root,
... | 11.857185 | 1.916902 | 6.185598 |
''' pause a running OciImage container, if it exists
Equivalent command line example:
singularity oci pause <container_ID>
Parameters
==========
container_id: the id to stop.
sudo: Add sudo to the command. If the container was created by root,
... | def pause(self, container_id=None, sudo=None) | pause a running OciImage container, if it exists
Equivalent command line example:
singularity oci pause <container_ID>
Parameters
==========
container_id: the id to stop.
sudo: Add sudo to the command. If the container was created by root,
... | 12.156063 | 1.925827 | 6.312128 |
'''stop ALL instances. This command is only added to the command group
as it doesn't make sense to call from a single instance
Parameters
==========
sudo: if the command should be done with sudo (exposes different set of
instances)
'''
from spython.utils import run... | def stopall(self, sudo=False, quiet=True) | stop ALL instances. This command is only added to the command group
as it doesn't make sense to call from a single instance
Parameters
==========
sudo: if the command should be done with sudo (exposes different set of
instances) | 7.846097 | 4.344526 | 1.805973 |
'''set the logging level based on the environment
Parameters
==========
quiet: boolean if True, set to quiet. Gets overriden by environment
setting, and only exists to define default
'''
if os.environ.get('MESSAGELEVEL') == "QUIET":
quiet = True
... | def init_level(self, quiet=False) | set the logging level based on the environment
Parameters
==========
quiet: boolean if True, set to quiet. Gets overriden by environment
setting, and only exists to define default | 16.14444 | 3.790614 | 4.259057 |
'''print will print the output, given that quiet is not True. This
function also serves to convert output in bytes to utf-8
Parameters
==========
output: the string to print
quiet: a runtime variable to over-ride the default.
'''
if isinstance(output,bytes):
outp... | def println(self, output, quiet=False) | print will print the output, given that quiet is not True. This
function also serves to convert output in bytes to utf-8
Parameters
==========
output: the string to print
quiet: a runtime variable to over-ride the default. | 8.264141 | 2.167545 | 3.812674 |
'''help prints the general function help, or help for a specific command
Parameters
==========
command: the command to get help for, if none, prints general help
'''
from spython.utils import check_install
check_install()
cmd = ['singularity','--help']
if command !=... | def help(self, command=None) | help prints the general function help, or help for a specific command
Parameters
==========
command: the command to get help for, if none, prints general help | 8.810743 | 4.811493 | 1.831187 |
''' The Instance client holds the Singularity Instance command group
The levels of verbosity (debug and quiet) are passed from the main
client via the environment variable MESSAGELEVEL.
'''
from spython.instance import Instance
from spython.main.base.logger import println
from spyt... | def generate_instance_commands() | The Instance client holds the Singularity Instance command group
The levels of verbosity (debug and quiet) are passed from the main
client via the environment variable MESSAGELEVEL. | 11.004177 | 6.816246 | 1.614404 |
'''compress will (properly) compress an image'''
if os.path.exists(image_path):
compressed_image = "%s.gz" %image_path
os.system('gzip -c -6 %s > %s' %(image_path, compressed_image))
return compressed_image
bot.exit("Cannot find image %s" %image_path) | def compress(self, image_path) | compress will (properly) compress an image | 5.180691 | 4.382695 | 1.182079 |
'''decompress will (properly) decompress an image'''
if not os.path.exists(image_path):
bot.exit("Cannot find image %s" %image_path)
extracted_file = image_path.replace('.gz','')
cmd = ['gzip','-d','-f', image_path]
result = self.run_command(cmd, quiet=quiet) # exits if return code... | def decompress(self, image_path, quiet=True) | decompress will (properly) decompress an image | 6.140942 | 5.350932 | 1.14764 |
'''generate a Robot Name for the instance to use, if the user doesn't
supply one.
'''
# If no name provided, use robot name
if name == None:
name = self.RobotNamer.generate()
self.name = name.replace('-','_') | def generate_name(self, name=None) | generate a Robot Name for the instance to use, if the user doesn't
supply one. | 11.432945 | 4.533828 | 2.521698 |
'''Extract any additional attributes to hold with the instance
from kwargs
'''
# If not given metadata, use instance.list to get it for container
if kwargs == None and hasattr(self, 'name'):
kwargs = self._list(self.name, quiet=True, return_json=True)
# A... | def _update_metadata(self, kwargs=None) | Extract any additional attributes to hold with the instance
from kwargs | 8.497512 | 6.079312 | 1.397775 |
'''
run will run the container, with or withour arguments (which
should be provided in a list)
Parameters
==========
image: full path to singularity image
args: args to include with the run
app: if not None, execute a command in context of an app
... | def run(self,
image = None,
args = None,
app = None,
sudo = False,
writable = False,
contain = False,
bind = None,
stream = False,
nv = False,
return_result=False) | run will run the container, with or withour arguments (which
should be provided in a list)
Parameters
==========
image: full path to singularity image
args: args to include with the run
app: if not None, execute a command in context of an app
writable: This ... | 6.427607 | 2.797756 | 2.297415 |
'''create an OCI bundle from SIF image
Parameters
==========
image: the container (sif) to mount
'''
return self._state_command(image, command="mount", sudo=sudo) | def mount(self, image, sudo=None) | create an OCI bundle from SIF image
Parameters
==========
image: the container (sif) to mount | 19.040077 | 5.409252 | 3.519909 |
'''This function serves as a wrapper around the DockerRecipe and
SingularityRecipe converters. We can either save to file if
args.outfile is defined, or print to the console if not.
'''
from spython.main.parse import ( DockerRecipe, SingularityRecipe )
# We need something to work with
... | def main(args, options, parser) | This function serves as a wrapper around the DockerRecipe and
SingularityRecipe converters. We can either save to file if
args.outfile is defined, or print to the console if not. | 5.253099 | 3.666821 | 1.432603 |
''' replace the command name from the group, alert the user of content,
and clean up empty spaces
'''
bot.debug('[in] %s' % line)
# Replace ACTION at beginning
line = re.sub('^%s' % action, '', line)
# Handle continuation lines without ACTION by padding wit... | def _setup(self, action, line) | replace the command name from the group, alert the user of content,
and clean up empty spaces | 15.247143 | 7.318421 | 2.083392 |
''' get the FROM container image name from a FROM line!
Parameters
==========
line: the line from the recipe file to parse for FROM
'''
fromHeader = self._setup('FROM', line)
# Singularity does not support AS level
self.fromHeader = re.sub("AS ... | def _from(self, line) | get the FROM container image name from a FROM line!
Parameters
==========
line: the line from the recipe file to parse for FROM | 14.945854 | 8.159029 | 1.831818 |
''' everything from RUN goes into the install list
Parameters
==========
line: the line from the recipe file to parse for FROM
'''
line = self._setup('RUN', line)
self.install += line | def _run(self, line) | everything from RUN goes into the install list
Parameters
==========
line: the line from the recipe file to parse for FROM | 33.662922 | 6.41318 | 5.249022 |
'''singularity doesn't have support for ARG, so instead will issue
a warning to the console for the user to export the variable
with SINGULARITY prefixed at build.
Parameters
==========
line: the line from the recipe file to parse for ARG
'''
... | def _arg(self, line) | singularity doesn't have support for ARG, so instead will issue
a warning to the console for the user to export the variable
with SINGULARITY prefixed at build.
Parameters
==========
line: the line from the recipe file to parse for ARG | 24.033785 | 5.172399 | 4.646545 |
'''env will parse a line that beings with ENV, indicative of one or
more environment variables.
Parameters
==========
line: the line from the recipe file to parse for ADD
'''
line = self._setup('ENV', line)
# Extract environment (list) f... | def _env(self, line) | env will parse a line that beings with ENV, indicative of one or
more environment variables.
Parameters
==========
line: the line from the recipe file to parse for ADD | 22.261522 | 8.007045 | 2.780242 |
'''parse_add will copy multiple files from one location to another.
This likely will need tweaking, as the files might need to be
mounted from some location before adding to the image.
The add command is done for an entire directory. It is also
possible to have mor... | def _copy(self, lines) | parse_add will copy multiple files from one location to another.
This likely will need tweaking, as the files might need to be
mounted from some location before adding to the image.
The add command is done for an entire directory. It is also
possible to have more than one ... | 11.129548 | 2.214906 | 5.024841 |
'''Add can also handle https, and compressed files.
Parameters
==========
line: the line from the recipe file to parse for ADD
'''
lines = self._setup('ADD', lines)
for line in lines:
values = line.split(" ")
frompath = values.p... | def _add(self, lines) | Add can also handle https, and compressed files.
Parameters
==========
line: the line from the recipe file to parse for ADD | 7.355619 | 4.738018 | 1.552468 |
'''add files is the underlying function called to add files to the
list, whether originally called from the functions to parse archives,
or https. We make sure that any local references are changed to
actual file locations before adding to the files list.
Parame... | def _add_files(self, source, dest) | add files is the underlying function called to add files to the
list, whether originally called from the functions to parse archives,
or https. We make sure that any local references are changed to
actual file locations before adding to the files list.
Parameters
... | 11.924055 | 3.888042 | 3.066853 |
'''will get the filename of an http address, and return a statement
to download it to some location
Parameters
==========
url: the source url to retrieve with curl
dest: the destination folder to put it in the image
'''
file_name = os.path... | def _parse_http(self, url, dest) | will get the filename of an http address, and return a statement
to download it to some location
Parameters
==========
url: the source url to retrieve with curl
dest: the destination folder to put it in the image | 7.682027 | 2.253438 | 3.409026 |
'''parse_targz will add a line to the install script to extract a
targz to a location, and also add it to the files.
Parameters
==========
targz: the targz to extract
dest: the location to extract it to
'''
# Add command to extract it
... | def _parse_archive(self, targz, dest) | parse_targz will add a line to the install script to extract a
targz to a location, and also add it to the files.
Parameters
==========
targz: the targz to extract
dest: the location to extract it to | 8.904863 | 3.357142 | 2.652513 |
'''the default action assumes a line that is either a command (a
continuation of a previous, for example) or a comment.
Parameters
==========
line: the line from the recipe file to parse to INSTALL
'''
if line.strip().startswith('#'):
... | def _default(self, line) | the default action assumes a line that is either a command (a
continuation of a previous, for example) or a comment.
Parameters
==========
line: the line from the recipe file to parse to INSTALL | 14.321884 | 2.505371 | 5.716472 |
'''We don't have logic for volume for Singularity, so we add as
a comment in the install, and a metadata value for the recipe
object
Parameters
==========
line: the line from the recipe file to parse to INSTALL
'''
volumes = self._setup... | def _volume(self, line) | We don't have logic for volume for Singularity, so we add as
a comment in the install, and a metadata value for the recipe
object
Parameters
==========
line: the line from the recipe file to parse to INSTALL | 19.756613 | 3.36271 | 5.875206 |
'''Again, just add to metadata, and comment in install.
Parameters
==========
line: the line from the recipe file to parse to INSTALL
'''
ports = self._setup('EXPOSE', line)
if len(ports) > 0:
self.ports += ports
return self._comme... | def _expose(self, line) | Again, just add to metadata, and comment in install.
Parameters
==========
line: the line from the recipe file to parse to INSTALL | 23.696516 | 5.434477 | 4.360404 |
'''A Docker WORKDIR command simply implies to cd to that location
Parameters
==========
line: the line from the recipe file to parse for WORKDIR
'''
workdir = self._setup('WORKDIR', line)
line = "cd %s" %(''.join(workdir))
self.install.append(li... | def _workdir(self, line) | A Docker WORKDIR command simply implies to cd to that location
Parameters
==========
line: the line from the recipe file to parse for WORKDIR | 15.990726 | 4.469997 | 3.577346 |
'''_label will parse a Dockerfile label
Parameters
==========
line: the line from the recipe file to parse for CMD
'''
label = self._setup('LABEL', line)
self.labels += [ label ] | def _label(self, line) | _label will parse a Dockerfile label
Parameters
==========
line: the line from the recipe file to parse for CMD | 26.747055 | 6.035772 | 4.431422 |
'''mapping will take the command from a Dockerfile and return a map
function to add it to the appropriate place. Any lines that don't
cleanly map are assumed to be comments.
Parameters
==========
line: the list that has been parsed into parts with _split_l... | def _get_mapping(self, line, parser=None, previous=None) | mapping will take the command from a Dockerfile and return a map
function to add it to the appropriate place. Any lines that don't
cleanly map are assumed to be comments.
Parameters
==========
line: the list that has been parsed into parts with _split_line
... | 5.640089 | 2.916389 | 1.933929 |
'''parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Since Docker also exports environment as we go,
... | def _parse(self) | parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Since Docker also exports environment as we go,
... | 27.319975 | 2.401771 | 11.374931 |
'''get the uri of an image, or the string (optional) that appears before
://. Optional. If none found, returns ''
'''
image = image or ''
uri = ''
match = re.match("^(?P<uri>.+)://", image)
if match:
uri = match.group('uri')
return uri | def get_uri(self, image) | get the uri of an image, or the string (optional) that appears before
://. Optional. If none found, returns '' | 10.08844 | 2.801 | 3.601727 |
'''remove_image_uri will return just the image name.
this will also remove all spaces from the uri.
'''
image = image or ''
uri = self.get_uri(image) or ''
image = image.replace('%s://' %uri,'', 1)
return image.strip('-').rstrip('/') | def remove_uri(self, image) | remove_image_uri will return just the image name.
this will also remove all spaces from the uri. | 10.39722 | 4.991913 | 2.082813 |
'''
simply split the uri from the image. Singularity handles
parsing of registry, namespace, image.
Parameters
==========
image: the complete image uri to load (e.g., docker://ubuntu)
'''
self._image = image
self.... | def parse_image_name(self, image) | simply split the uri from the image. Singularity handles
parsing of registry, namespace, image.
Parameters
==========
image: the complete image uri to load (e.g., docker://ubuntu) | 13.964445 | 2.63842 | 5.292731 |
'''return an md5 hash of the file based on a criteria level. This
is intended to give the file a reasonable version. This only is
useful for actual image files.
Parameters
==========
image: the image path to get hash for (first priority). Second
... | def get_hash(self, image=None) | return an md5 hash of the file based on a criteria level. This
is intended to give the file a reasonable version. This only is
useful for actual image files.
Parameters
==========
image: the image path to get hash for (first priority). Second
... | 7.671464 | 2.047613 | 3.74654 |
'''
return list of SCIF apps in image. The Singularity software serves
a scientific filesystem integration that will install apps to
/scif/apps and associated data to /scif/data. For more information
about SCIF, see https://sci-f.github.io
Parameters
==========
ful... | def apps(self, image=None, full_path=False, root='') | return list of SCIF apps in image. The Singularity software serves
a scientific filesystem integration that will install apps to
/scif/apps and associated data to /scif/data. For more information
about SCIF, see https://sci-f.github.io
Parameters
==========
full_path: if True... | 7.753265 | 2.721048 | 2.849367 |
'''create will create a a new image
Parameters
==========
image_path: full path to image
size: image sizein MiB, default is 1024MiB
filesystem: supported file systems ext3/ext4 (ext[2/3]: default ext3
'''
from spython.utils import check_install
check_ins... | def create(self,image_path, size=1024, sudo=False) | create will create a a new image
Parameters
==========
image_path: full path to image
size: image sizein MiB, default is 1024MiB
filesystem: supported file systems ext3/ext4 (ext[2/3]: default ext3 | 7.807512 | 3.678894 | 2.122244 |
'''check_install will attempt to run the singularity command, and
return True if installed. The command line utils will not run
without this check.
'''
cmd = [software, '--version']
found = False
try:
version = run_command(cmd, quiet=True)
except: # FileNotFoundError
... | def check_install(software='singularity', quiet=True) | check_install will attempt to run the singularity command, and
return True if installed. The command line utils will not run
without this check. | 6.380969 | 3.620995 | 1.762214 |
'''get the singularity client version. Useful in the case that functionality
has changed, etc. Can be "hacked" if needed by exporting
SPYTHON_SINGULARITY_VERSION, which is checked before checking on the
command line.
'''
version = os.environ.get('SPYTHON_SINGULARITY_VERSION', "")
i... | def get_singularity_version() | get the singularity client version. Useful in the case that functionality
has changed, etc. Can be "hacked" if needed by exporting
SPYTHON_SINGULARITY_VERSION, which is checked before checking on the
command line. | 7.237332 | 2.657291 | 2.723575 |
'''stream a command (yield) back to the user, as each line is available.
# Example usage:
results = []
for line in stream_command(cmd):
print(line, end="")
results.append(line)
Parameters
==========
cmd: the command to send, should be a list for subp... | def stream_command(cmd, no_newline_regexp="Progess", sudo=False) | stream a command (yield) back to the user, as each line is available.
# Example usage:
results = []
for line in stream_command(cmd):
print(line, end="")
results.append(line)
Parameters
==========
cmd: the command to send, should be a list for subprocess
... | 3.657169 | 1.637302 | 2.233657 |
'''run_command uses subprocess to send a command to the terminal. If
capture is True, we use the parent stdout, so the progress bar (and
other commands of interest) are piped to the user. This means we
don't return the output to parse.
Parameters
==========
cmd: the comm... | def run_command(cmd,
sudo=False,
capture=True,
no_newline_regexp="Progess",
quiet=False) | run_command uses subprocess to send a command to the terminal. If
capture is True, we use the parent stdout, so the progress bar (and
other commands of interest) are piped to the user. This means we
don't return the output to parse.
Parameters
==========
cmd: the command to s... | 5.09929 | 1.897388 | 2.687531 |
'''get_requirements reads in requirements and versions from
the lookup obtained with get_lookup'''
if lookup == None:
lookup = get_lookup()
install_requires = []
for module in lookup['INSTALL_REQUIRES']:
module_name = module[0]
module_meta = module[1]
if "exact_vers... | def get_requirements(lookup=None) | get_requirements reads in requirements and versions from
the lookup obtained with get_lookup | 2.959792 | 2.318492 | 1.276602 |
'''load an image, either an actual path on the filesystem or a uri.
Parameters
==========
image: the image path or uri to load (e.g., docker://ubuntu
'''
from spython.image import Image
from spython.instance import Instance
self.simage = Image(image)
if image is not Non... | def load(self, image=None) | load an image, either an actual path on the filesystem or a uri.
Parameters
==========
image: the image path or uri to load (e.g., docker://ubuntu | 9.28265 | 4.77056 | 1.94582 |
'''set an environment variable for Singularity
Parameters
==========
variable: the variable to set
value: the value to set
'''
os.environ[variable] = value
os.putenv(variable, value)
bot.debug('%s set to %s' % (variable, value)) | def setenv(self, variable, value) | set an environment variable for Singularity
Parameters
==========
variable: the variable to set
value: the value to set | 5.092955 | 3.513938 | 1.449358 |
''' check if the loaded image object (self.simage) has an associated uri
return if yes, None if not.
'''
if hasattr(self, 'simage'):
if self.simage is not None:
if self.simage.image not in ['', None]:
# Concatenates the <uri>://<image>
return str(s... | def get_uri(self) | check if the loaded image object (self.simage) has an associated uri
return if yes, None if not. | 9.783039 | 4.32499 | 2.261979 |
'''parse_verbosity will take an argument object, and return the args
passed (from a dictionary) to a list
Parameters
==========
args: the argparse argument objects
'''
flags = []
if args.silent is True:
flags.append('--silent')
elif args.quiet is True:
... | def parse_verbosity(self, args) | parse_verbosity will take an argument object, and return the args
passed (from a dictionary) to a list
Parameters
==========
args: the argparse argument objects | 5.609828 | 2.560637 | 2.190794 |
''' The oci command group will allow interaction with an image using
OCI commands.
'''
from spython.oci import OciImage
from spython.main.base.logger import println
# run_command uses run_cmd, but wraps to catch error
from spython.main.base.command import ( run_command, send_command )
... | def generate_oci_commands() | The oci command group will allow interaction with an image using
OCI commands. | 4.65195 | 4.115308 | 1.130401 |
'''convert a Singularity recipe to a (best estimated) Dockerfile'''
recipe = [ "FROM %s" %self.fromHeader ]
# Comments go up front!
recipe += self.comments
# First add files, labels
recipe += write_lines('ADD', self.files)
recipe += write_lines('LABEL', self.labels)
recipe += write_... | def singularity2docker(self, runscript="/bin/bash", force=False) | convert a Singularity recipe to a (best estimated) Dockerfile | 8.267765 | 6.979428 | 1.184591 |
'''write a list of lines with a header for a section.
Parameters
==========
lines: one or more lines to write, with header appended
'''
result = []
continued = False
for line in lines:
if continued:
result.append(line)
else:
result.a... | def write_lines(label, lines) | write a list of lines with a header for a section.
Parameters
==========
lines: one or more lines to write, with header appended | 4.982404 | 2.913193 | 1.71029 |
'''create_entrypoint is intended to create a singularity runscript
based on a Docker entrypoint or command. We first use the Docker
ENTRYPOINT, if defined. If not, we use the CMD. If neither is found,
we use function default.
Parameters
==========
default: set a default en... | def create_runscript(self, default="/bin/bash", force=False) | create_entrypoint is intended to create a singularity runscript
based on a Docker entrypoint or command. We first use the Docker
ENTRYPOINT, if defined. If not, we use the CMD. If neither is found,
we use function default.
Parameters
==========
default: set a default entrypoin... | 7.848205 | 3.070869 | 2.555695 |
'''create a section based on key, value recipe pairs,
This is used for files or label
Parameters
==========
attribute: the name of the data section, either labels or files
name: the name to write to the recipe file (e.g., %name).
if not defined, the attribute name is use... | def create_section(self, attribute, name=None) | create a section based on key, value recipe pairs,
This is used for files or label
Parameters
==========
attribute: the name of the data section, either labels or files
name: the name to write to the recipe file (e.g., %name).
if not defined, the attribute name is used. | 8.03537 | 4.038916 | 1.989487 |
'''finish_section will add the header to a section, to finish the recipe
take a custom command or list and return a section.
Parameters
==========
section: the section content, without a header
name: the name of the section for the header
'''
if not isinstance(section... | def finish_section(section, name) | finish_section will add the header to a section, to finish the recipe
take a custom command or list and return a section.
Parameters
==========
section: the section content, without a header
name: the name of the section for the header | 13.856107 | 2.898001 | 4.781263 |
'''create a section based on key, value recipe pairs,
This is used for files or label
Parameters
==========
section: the list of values to return as a parsed list of lines
name: the name of the section to write (e.g., files)
'''
section = ['%' + name ]
for pair in pairs... | def create_keyval_section(pairs, name) | create a section based on key, value recipe pairs,
This is used for files or label
Parameters
==========
section: the list of values to return as a parsed list of lines
name: the name of the section to write (e.g., files) | 13.839599 | 2.849583 | 4.856709 |
'''environment key value pairs need to be joined by an equal, and
exported at the end.
Parameters
==========
section: the list of values to return as a parsed list of lines
name: the name of the section to write (e.g., files)
'''
section = ['%' + name ]
for pair in pair... | def create_env_section(pairs, name) | environment key value pairs need to be joined by an equal, and
exported at the end.
Parameters
==========
section: the list of values to return as a parsed list of lines
name: the name of the section to write (e.g., files) | 15.247137 | 2.925048 | 5.212611 |
'''docker2singularity will return a Singularity build recipe based on
a the loaded recipe object. It doesn't take any arguments as the
recipe object contains the sections, and the calling function
determines saving / output logic.
'''
recipe = ['Bootstrap: docker']
recipe += [ "Fr... | def docker2singularity(self, runscript="/bin/bash", force=False) | docker2singularity will return a Singularity build recipe based on
a the loaded recipe object. It doesn't take any arguments as the
recipe object contains the sections, and the calling function
determines saving / output logic. | 10.664465 | 5.099061 | 2.091456 |
return "%s-%s" % (re.sub('[^\w.]', '', datetime.now().isoformat()).replace(".", "Z-"), new_uid(bits)) | def new_timestamped_uid(bits=32) | A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of
randomness. The advantage of this is it sorts nicely by time, while still being unique.
Example: 20150912T084555Z-378465-43vtwbx | 8.8853 | 9.352724 | 0.950023 |
if not string or not max_len or len(string) <= max_len:
return string
elif max_len <= len(indicator):
return string[0:max_len]
else:
return string[0:max_len - len(indicator)] + indicator | def abbreviate_str(string, max_len=80, indicator="...") | Abbreviate a string, adding an indicator like an ellipsis if required. | 2.476681 | 2.189726 | 1.131046 |
if not items:
return items
else:
shortened = [abbreviate_str("%s" % item, max_len=item_max_len) for item in items[0:max_items]]
if len(items) > max_items:
shortened.append(indicator)
return joiner.join(shortened) | def abbreviate_list(items, max_items=10, item_max_len=40, joiner=", ", indicator="...") | Abbreviate a list, truncating each element and adding an indicator at the end if the
whole list was truncated. Set item_max_len to None or 0 not to truncate items. | 2.415026 | 2.352283 | 1.026673 |
if template_str is None:
return None
else:
if transformer is None:
transformer = lambda v: v
try:
# Don't bother iterating items for Python 2+3 compatibility.
transformed_value_map = {k: transformer(value_map[k]) for k in value_map}
return Template(template_str).substitute(tra... | def expand_variables(template_str, value_map, transformer=None) | Expand a template string like "blah blah $FOO blah" using given value mapping. | 3.614875 | 3.456297 | 1.045881 |
return [expand_variables(item, values) for item in shlex.split(template)] | def shell_expand_to_popen(template, values) | Expand a template like "cp $SOURCE $TARGET/blah" into a list of popen arguments. | 6.706645 | 5.66352 | 1.184183 |
if backup_suffix and os.path.exists(path):
backup_path = path + backup_suffix
# Some messy corner cases need to be handled for existing backups.
# TODO: Note if this is a directory, and we do this twice at once, there is a potential race
# that could leave one backup inside the other.
if os.pat... | def move_to_backup(path, backup_suffix=BACKUP_SUFFIX) | Move the given file or directory to the same name, with a backup suffix.
If backup_suffix not supplied, move it to the extension ".bak".
NB: If backup_suffix is supplied and is None, don't do anything. | 4.640954 | 4.619931 | 1.004551 |
# Avoid races inherent to doing this in two steps (check then create).
# Python 3 has exist_ok but the approach below works for Python 2+3.
# https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
try:
os.makedirs(path, mode=mode)
except OSError as e:
if e.errno == errno.EEXIST ... | def make_all_dirs(path, mode=0o777) | Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists. | 4.232748 | 4.069954 | 1.039999 |
parent = os.path.dirname(path)
if parent:
make_all_dirs(parent, mode)
return path | def make_parent_dirs(path, mode=0o777) | Ensure parent directories of a file are created as needed. | 4.386332 | 3.9158 | 1.120162 |
if dest_path == os.devnull:
# Handle the (probably rare) case of writing to /dev/null.
yield dest_path
else:
tmp_path = ("%s" + suffix) % (dest_path, new_uid())
if make_parents:
make_parent_dirs(tmp_path)
yield tmp_path
# Note this is not in a finally block, so that result won't b... | def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s") | A context manager for convenience in writing a file or directory in an atomic way. Set up
a temporary name, then rename it after the operation is done, optionally making a backup of
the previous file or directory, if present. | 4.060838 | 3.91431 | 1.037434 |
return _temp_output(False, prefix=prefix, suffix=suffix, dir=dir, make_parents=make_parents,
always_clean=always_clean) | def temp_output_file(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False) | A context manager for convenience in creating a temporary file,
which is deleted when exiting the context.
Usage:
with temp_output_file() as (fd, path):
... | 2.989358 | 6.095438 | 0.490425 |
return _temp_output(True, prefix=prefix, suffix=suffix, dir=dir, make_parents=make_parents,
always_clean=always_clean) | def temp_output_dir(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False) | A context manager for convenience in creating a temporary directory,
which is deleted when exiting the context.
Usage:
with temp_output_dir() as dirname:
... | 3.047746 | 5.962112 | 0.511186 |
with codecs.open(path, "rb", encoding=encoding) as f:
value = f.read()
return value | def read_string_from_file(path, encoding="utf8") | Read entire contents of file into a string. | 3.397278 | 3.310477 | 1.02622 |
with atomic_output_file(path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
with codecs.open(tmp_path, "wb", encoding=encoding) as f:
f.write(string) | def write_string_to_file(path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8") | Write entire file with given string contents, atomically. Keeps backup by default. | 2.307094 | 2.117357 | 1.08961 |
if not atime:
atime = mtime
f = open(path, 'a')
try:
os.utime(path, (atime, mtime))
finally:
f.close() | def set_file_mtime(path, mtime, atime=None) | Set access and modification times on a file. | 2.147285 | 1.976942 | 1.086165 |
with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
shutil.copyfile(source_path, tmp_path)
set_file_mtime(tmp_path, os.path.getmtime(source_path)) | def copyfile_atomic(source_path, dest_path, make_parents=False, backup_suffix=None) | Copy file on local filesystem in an atomic way, so partial copies never exist. Preserves timestamps. | 2.134426 | 2.070286 | 1.030981 |
if os.path.isdir(source_path):
with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
shutil.copytree(source_path, tmp_path, symlinks=symlinks)
else:
copyfile_atomic(source_path, dest_path, make_parents=make_parents, backup_suffix=backup_suffix) | def copytree_atomic(source_path, dest_path, make_parents=False, backup_suffix=None, symlinks=False) | Copy a file or directory recursively, and atomically, reanaming file or top-level dir when done.
Unlike shutil.copytree, this will not fail on a file. | 1.867751 | 1.78811 | 1.044539 |
if make_parents:
make_parent_dirs(dest_path)
move_to_backup(dest_path, backup_suffix=backup_suffix)
shutil.move(source_path, dest_path) | def movefile(source_path, dest_path, make_parents=False, backup_suffix=None) | Move file. With a few extra options. | 2.524786 | 2.342444 | 1.077842 |
# TODO: Could add an rsync-based delete, as in
# https://github.com/vivlabs/instaclone/blob/master/instaclone/instaclone.py#L127-L143
if ignore_errors and not os.path.exists(path):
return
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path, ignore_errors=ignore_errors, onerror=one... | def rmtree_or_file(path, ignore_errors=False, onerror=None) | rmtree fails on files or symlinks. This removes the target, whatever it is. | 3.490674 | 3.283093 | 1.063227 |
popenargs = ["chmod"]
if recursive:
popenargs.append("-R")
popenargs.append(mode_expression)
popenargs.append(path)
subprocess.check_call(popenargs) | def chmod_native(path, mode_expression, recursive=False) | This is ugly and will only work on POSIX, but the built-in Python os.chmod support
is very minimal, and neither supports fast recursive chmod nor "+X" type expressions,
both of which are slow for large trees. So just shell out. | 2.286197 | 2.197772 | 1.040234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.