Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def modify_file_in_place(self, fp, length, iso_path, rr_name=None, # pylint: disable=unused-argument
joliet_path=None, udf_path=None): # pylint: disable=unused-argument
# type: (BinaryIO, int, str, Optional[str], Optional[str], ... | [] |
Please provide a description of the function:def add_hard_link(self, **kwargs):
# type: (Any) -> None
'''
Add a hard link to the ISO. Hard links are alternate names for the
same file contents that don't take up any additional space on the the
ISO. This API can be used to create... | [] |
Please provide a description of the function:def rm_hard_link(self, iso_path=None, joliet_path=None, udf_path=None):
# type: (Optional[str], Optional[str], Optional[str]) -> None
'''
Remove a hard link from the ISO. If the number of links to a piece of
data drops to zero, then the conte... | [] |
Please provide a description of the function:def add_directory(self, iso_path=None, rr_name=None, joliet_path=None,
file_mode=None, udf_path=None):
# type: (Optional[str], Optional[str], Optional[str], int, Optional[str]) -> None
'''
Add a directory to the ISO. At least on... | [] |
Please provide a description of the function:def rm_file(self, iso_path, rr_name=None, joliet_path=None, udf_path=None): # pylint: disable=unused-argument
# type: (str, Optional[str], Optional[str], Optional[str]) -> None
'''
Remove a file from the ISO.
Parameters:
iso_path - ... | [] |
Please provide a description of the function:def rm_directory(self, iso_path=None, rr_name=None, joliet_path=None, udf_path=None):
# type: (Optional[str], Optional[str], Optional[str], Optional[str]) -> None
'''
Remove a directory from the ISO.
Parameters:
iso_path - The path t... | [] |
Please provide a description of the function:def add_eltorito(self, bootfile_path, bootcatfile=None,
rr_bootcatname=None, joliet_bootcatfile=None,
boot_load_size=None, platform_id=0, boot_info_table=False,
efi=False, media_name='noemul', bootable=True,
... | [] |
Please provide a description of the function:def rm_eltorito(self):
# type: () -> None
'''
Remove the El Torito boot record (and Boot Catalog) from the ISO.
Parameters:
None.
Returns:
Nothing.
'''
if not self._initialized:
raise pycd... | [] |
Please provide a description of the function:def list_dir(self, iso_path, joliet=False):
# type: (str, bool) -> Generator
'''
(deprecated) Generate a list of all of the file/directory objects in the
specified location on the ISO. It is recommended to use the
'list_children' API ... | [] |
Please provide a description of the function:def list_children(self, **kwargs):
# type: (str) -> Generator
'''
Generate a list of all of the file/directory objects in the
specified location on the ISO.
Parameters:
iso_path - The absolute path on the ISO to list the chil... | [] |
Please provide a description of the function:def get_entry(self, iso_path, joliet=False):
# type: (str, bool) -> dr.DirectoryRecord
'''
(deprecated) Get the directory record for a particular path. It is
recommended to use the 'get_record' API instead.
Parameters:
iso_p... | [] |
Please provide a description of the function:def get_record(self, **kwargs):
# type: (str) -> Union[dr.DirectoryRecord, udfmod.UDFFileEntry]
'''
Get the directory record for a particular path.
Parameters:
iso_path - The absolute path on the ISO9660 filesystem to get the
... | [] |
Please provide a description of the function:def add_isohybrid(self, part_entry=1, mbr_id=None, part_offset=0,
geometry_sectors=32, geometry_heads=64, part_type=0x17,
mac=False):
# type: (int, Optional[int], int, int, int, int, bool) -> None
'''
Make a... | [] |
Please provide a description of the function:def full_path_from_dirrecord(self, rec, rockridge=False):
# type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry], bool) -> str
'''
A method to get the absolute path of a directory record.
Parameters:
rec - The directory record to ge... | [] |
Please provide a description of the function:def duplicate_pvd(self):
# type: () -> None
'''
A method to add a duplicate PVD to the ISO. This is a mostly useless
feature allowed by Ecma-119 to have duplicate PVDs to avoid possible
corruption.
Parameters:
None.
... | [] |
Please provide a description of the function:def clear_hidden(self, iso_path=None, rr_path=None, joliet_path=None):
# type: (Optional[str], Optional[str], Optional[str]) -> None
'''
Clear the ISO9660 hidden attribute on a file or directory. This will
cause the file or directory to show ... | [] |
Please provide a description of the function:def set_relocated_name(self, name, rr_name):
# type: (str, str) -> None
'''
Set the name of the relocated directory on a Rock Ridge ISO. The ISO
must be a Rock Ridge one, and must not have previously had the relocated
name set.
... | [] |
Please provide a description of the function:def walk(self, **kwargs):
# type: (str) -> Generator
'''
Walk the entries on the ISO, starting at the given path. One, and only
one, of iso_path, rr_path, joliet_path, and udf_path is allowed.
Similar to os.walk(), yield a 3-tuple of ... | [] |
Please provide a description of the function:def open_file_from_iso(self, **kwargs):
# type: (str) -> PyCdlibIO
'''
Open a file for reading in a context manager. This allows the user to
operate on the file in user-defined chunks (utilizing the read() method
of the returned conte... | [] |
Please provide a description of the function:def close(self):
# type: () -> None
'''
Close the PyCdlib object, and re-initialize the object to the defaults.
The object can then be re-used for manipulation of another ISO.
Parameters:
None.
Returns:
Nothi... | [] |
Please provide a description of the function:def make_arg_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
usage="vex [OPTIONS] VIRTUALENV_NAME COMMAND_TO_RUN ...",
)
make = parser.add_argument_group(title='To make a new virtualenv')
make.a... | [
"Return a standard ArgumentParser object.\n "
] |
Please provide a description of the function:def get_options(argv):
arg_parser = make_arg_parser()
options, unknown = arg_parser.parse_known_args(argv)
if unknown:
arg_parser.print_help()
raise exceptions.UnknownArguments(
"unknown args: {0!r}".format(unknown))
options.p... | [
"Called to parse the given list as command-line arguments.\n\n :returns:\n an options object as returned by argparse.\n "
] |
Please provide a description of the function:def _update_bird_conf_file(self, operation):
conf_updated = False
prefixes = []
ip_version = operation.ip_version
config_file = self.bird_configuration[ip_version]['config_file']
variable_name = self.bird_configuration[ip_vers... | [
"Update BIRD configuration.\n\n It adds to or removes IP prefix from BIRD configuration. It also\n updates generation time stamp in the configuration file.\n\n Main program will exit if configuration file cant be read/written.\n\n Arguments:\n operation (obj): Either an AddOpe... |
Please provide a description of the function:def run(self):
# Lunch a thread for each configuration
if not self.services:
self.log.warning("no service checks are configured")
else:
self.log.info("going to lunch %s threads", len(self.services))
if self... | [
"Lunch checks and triggers updates on BIRD configuration."
] |
Please provide a description of the function:def valid_ip_prefix(ip_prefix):
try:
ip_prefix = ipaddress.ip_network(ip_prefix)
except ValueError:
return False
else:
if ip_prefix.version == 4 and ip_prefix.max_prefixlen != 32:
return False
if ip_prefix.version ... | [
"Perform a sanity check on ip_prefix.\n\n Arguments:\n ip_prefix (str): The IP-Prefix to validate\n\n Returns:\n True if ip_prefix is a valid IPv4 address with prefix length 32 or a\n valid IPv6 address with prefix length 128, otherwise False\n\n "
] |
Please provide a description of the function:def get_ip_prefixes_from_config(config, services, ip_version):
ip_prefixes = set()
for service in services:
ip_prefix = ipaddress.ip_network(config.get(service, 'ip_prefix'))
if ip_prefix.version == ip_version:
ip_prefixes.add(ip_pre... | [
"Build a set of IP prefixes found in service configuration files.\n\n Arguments:\n config (obg): A configparser object which holds our configuration.\n services (list): A list of section names which are the name of the\n service checks.\n ip_version (int): IP protocol version\n\n R... |
Please provide a description of the function:def ip_prefixes_sanity_check(config, bird_configuration):
for ip_version in bird_configuration:
modify_ip_prefixes(config,
bird_configuration[ip_version]['config_file'],
bird_configuration[ip_version]['va... | [
"Sanity check on IP prefixes.\n\n Arguments:\n config (obg): A configparser object which holds our configuration.\n bird_configuration (dict): A dictionary, which holds Bird configuration\n per IP protocol version.\n\n "
] |
Please provide a description of the function:def modify_ip_prefixes(
config,
config_file,
variable_name,
dummy_ip_prefix,
reconfigure_cmd,
keep_changes,
changes_counter,
ip_version):
log = logging.getLogger(PROGRAM_NAME)
services = config.sect... | [
"Modify IP prefixes in Bird configuration.\n\n Depending on the configuration either removes or reports IP prefixes found\n in Bird configuration for which we don't have a service check associated\n with them. Moreover, it adds the dummy IP prefix if it isn't present and\n ensures that the correct varia... |
Please provide a description of the function:def load_configuration(config_file, config_dir, service_file):
config_files = [config_file]
config = configparser.ConfigParser()
config.read_dict(DEFAULT_OPTIONS)
if not os.path.isfile(config_file):
raise ValueError("{f} configuration file eithe... | [
"Build configuration objects.\n\n If all sanity checks against daemon and service check settings are passed\n then it builds a ConfigParser object which holds all our configuration\n and a dictionary data structure which holds Bird configuration per IP\n protocol version.\n\n Arguments:\n conf... |
Please provide a description of the function:def configuration_check(config):
log_level = config.get('daemon', 'loglevel')
num_level = getattr(logging, log_level.upper(), None)
pidfile = config.get('daemon', 'pidfile')
# Catch the case where the directory, under which we store the pid file, is
... | [
"Perform a sanity check on configuration.\n\n First it performs a sanity check against settings for daemon\n and then against settings for each service check.\n\n Arguments:\n config (obj): A configparser object which holds our configuration.\n\n Returns:\n None if all checks are successfu... |
Please provide a description of the function:def service_configuration_check(config):
ipv4_enabled = config.getboolean('daemon', 'ipv4')
ipv6_enabled = config.getboolean('daemon', 'ipv6')
services = config.sections()
# we don't need it during sanity check for services check
services.remove('dae... | [
"Perform a sanity check against options for each service check.\n\n Arguments:\n config (obj): A configparser object which holds our configuration.\n\n Returns:\n None if all sanity checks are successfully passed otherwise raises a\n ValueError exception.\n\n "
] |
Please provide a description of the function:def build_bird_configuration(config):
bird_configuration = {}
if config.getboolean('daemon', 'ipv4'):
if os.path.islink(config.get('daemon', 'bird_conf')):
config_file = os.path.realpath(config.get('daemon', 'bird_conf'))
print("... | [
"Build bird configuration structure.\n\n First it performs a sanity check against bird settings and then builds a\n dictionary structure with bird configuration per IP version.\n\n Arguments:\n config (obj): A configparser object which holds our configuration.\n\n Returns:\n A dictionary\n... |
Please provide a description of the function:def get_variable_name_from_bird(bird_conf):
bird_variable_pattern = re.compile(
r'''
^\s*
define\s+
(?P<name>\S+\b)
\s+
=
''', re.VERBOSE
)
with open(bird_conf, 'r') as content:
for line in con... | [
"Return the variable name set in Bird configuration.\n\n The variable name in Bird configuration is set with the keyword 'define',\n here is an example:\n\n define ACAST_PS_ADVERTISE =\n\n and we exract the string between the word 'define' and the equals sign.\n\n Arguments:\n bird_conf (s... |
Please provide a description of the function:def create_bird_config_files(bird_configuration):
for ip_version in bird_configuration:
# This creates the file if it doesn't exist.
config_file = bird_configuration[ip_version]['config_file']
try:
touch(config_file)
excep... | [
"Create bird configuration files per IP version.\n\n Creates bird configuration files if they don't exist. It also creates the\n directories where we store the history of changes, if this functionality is\n enabled.\n\n Arguments:\n bird_configuration (dict): A dictionary with settings for bird.\... |
Please provide a description of the function:def running(processid):
try:
# From kill(2)
# If sig is 0 (the null signal), error checking is performed but no
# signal is actually sent. The null signal can be used to check the
# validity of pid
os.kill(processid, 0)
... | [
"Check the validity of a process ID.\n\n Arguments:\n processid (int): Process ID number.\n\n Returns:\n True if process ID is found otherwise False.\n\n "
] |
Please provide a description of the function:def get_ip_prefixes_from_bird(filename):
prefixes = []
with open(filename, 'r') as bird_conf:
lines = bird_conf.read()
for line in lines.splitlines():
line = line.strip(', ')
if valid_ip_prefix(line):
prefixes.append(line... | [
"Build a list of IP prefixes found in Bird configuration.\n\n Arguments:\n filename (str): The absolute path of the Bird configuration file.\n\n Notes:\n It can only parse a file with the following format\n\n define ACAST_PS_ADVERTISE =\n [\n 10.189.2... |
Please provide a description of the function:def reconfigure_bird(cmd):
log = logging.getLogger(PROGRAM_NAME)
cmd = shlex.split(cmd)
log.info("reconfiguring BIRD by running %s", ' '.join(cmd))
try:
output = subprocess.check_output(
cmd,
timeout=2,
stderr=... | [
"Reconfigure BIRD daemon.\n\n Arguments:\n cmd (string): A command to trigger a reconfiguration of Bird daemon\n\n Notes:\n Runs 'birdc configure' to reconfigure BIRD. Some useful information on\n how birdc tool works:\n -- Returns a non-zero exit code only when it can't access... |
Please provide a description of the function:def write_temp_bird_conf(dummy_ip_prefix,
config_file,
variable_name,
prefixes):
log = logging.getLogger(PROGRAM_NAME)
comment = ("# {i} is a dummy IP Prefix. It should NOT be used and "
... | [
"Write in a temporary file the list of IP-Prefixes.\n\n A failure to create and write the temporary file will exit main program.\n\n Arguments:\n dummy_ip_prefix (str): The dummy IP prefix, which must be always\n config_file (str): The file name of bird configuration\n variable_name (str)... |
Please provide a description of the function:def archive_bird_conf(config_file, changes_counter):
log = logging.getLogger(PROGRAM_NAME)
history_dir = os.path.join(os.path.dirname(config_file), 'history')
dst = os.path.join(history_dir, str(time.time()))
log.debug("coping %s to %s", config_file, dst... | [
"Keep a history of Bird configuration files.\n\n Arguments:\n config_file (str): file name of bird configuration\n changes_counter (int): number of configuration files to keep in the\n history\n "
] |
Please provide a description of the function:def update_pidfile(pidfile):
try:
with open(pidfile, mode='r') as _file:
pid = _file.read(1024).rstrip()
try:
pid = int(pid)
except ValueError:
print("cleaning stale pidfile with invalid data:'{}'".format(... | [
"Update pidfile.\n\n Notice:\n We should call this function only after we have successfully acquired\n a lock and never before. It exits main program if it fails to parse\n and/or write pidfile.\n\n Arguments:\n pidfile (str): pidfile to update\n\n "
] |
Please provide a description of the function:def write_pid(pidfile):
pid = str(os.getpid())
try:
with open(pidfile, mode='w') as _file:
print("writing processID {p} to pidfile".format(p=pid))
_file.write(pid)
except OSError as exc:
sys.exit("failed to write pidfi... | [
"Write processID to the pidfile.\n\n Notice:\n It exits main program if it fails to write pidfile.\n\n Arguments:\n pidfile (str): pidfile to update\n\n "
] |
Please provide a description of the function:def shutdown(pidfile, signalnb=None, frame=None):
log = logging.getLogger(PROGRAM_NAME)
log.info("received %s at %s", signalnb, frame)
log.info("going to remove pidfile %s", pidfile)
# no point to catch possible errors when we delete the pid file
os.... | [
"Clean up pidfile upon shutdown.\n\n Notice:\n We should register this function as signal handler for the following\n termination signals:\n SIGHUP\n SIGTERM\n SIGABRT\n SIGINT\n\n Arguments:\n pidfile (str): pidfile to remove\n signalnb ... |
Please provide a description of the function:def setup_logger(config):
logger = logging.getLogger(PROGRAM_NAME)
num_level = getattr(
logging,
config.get('daemon', 'loglevel').upper(), # pylint: disable=no-member
None
)
logger.setLevel(num_level)
lengths = []
for sec... | [
"Configure the logging environment.\n\n Notice:\n By default logging will go to STDOUT and messages for unhandled\n exceptions or crashes will go to STDERR. If log_file and/or log_server\n is set then we don't log to STDOUT. Messages for unhandled exceptions\n or crashes can only go t... |
Please provide a description of the function:def run_custom_bird_reconfigure(operation):
log = logging.getLogger(PROGRAM_NAME)
if isinstance(operation, AddOperation):
status = 'up'
else:
status = 'down'
cmd = shlex.split(operation.bird_reconfigure_cmd + " " + status)
log.info("r... | [
"Reconfigure BIRD daemon by running a custom command.\n\n It adds one argument to the command, either \"up\" or \"down\".\n If command times out then we kill it. In order to avoid leaving any orphan\n processes, that may have been started by the command, we start a new\n session when we invoke the comma... |
Please provide a description of the function:def update(self, prefixes):
if self.ip_prefix not in prefixes:
prefixes.append(self.ip_prefix)
self.log.info("announcing %s for %s", self.ip_prefix, self.name)
return True
return False | [
"Add a value to the list.\n\n Arguments:\n prefixes(list): A list to add the value\n "
] |
Please provide a description of the function:def write(self, string):
string = string.rstrip()
if string: # Don't log empty lines
self.logger.critical(string) | [
"Erase newline from a string and write to the logger."
] |
Please provide a description of the function:def process_log_record(self, log_record):
log_record["version"] = __version__
log_record["program"] = PROGRAM_NAME
log_record["service_name"] = log_record.pop('threadName', None)
# return jsonlogger.JsonFormatter.process_log_record(se... | [
"Add customer record keys and rename threadName key."
] |
Please provide a description of the function:def get_vexrc(options, environ):
# Complain if user specified nonexistent file with --config.
# But we don't want to complain just because ~/.vexrc doesn't exist.
if options.config and not os.path.exists(options.config):
raise exceptions.InvalidVexrc... | [
"Get a representation of the contents of the config file.\n\n :returns:\n a Vexrc instance.\n "
] |
Please provide a description of the function:def get_cwd(options):
if not options.cwd:
return None
if not os.path.exists(options.cwd):
raise exceptions.InvalidCwd(
"can't --cwd to invalid path {0!r}".format(options.cwd))
return options.cwd | [
"Discover what directory the command should run in.\n "
] |
Please provide a description of the function:def get_virtualenv_path(ve_base, ve_name):
if not ve_base:
raise exceptions.NoVirtualenvsDirectory(
"could not figure out a virtualenvs directory. "
"make sure $HOME is set, or $WORKON_HOME,"
" or set virtualenvs=something... | [
"Check a virtualenv path, raising exceptions to explain problems.\n "
] |
Please provide a description of the function:def get_command(options, vexrc, environ):
command = options.rest
if not command:
command = vexrc.get_shell(environ)
if command and command[0].startswith('--'):
raise exceptions.InvalidCommand(
"don't put flags like '%s' after the ... | [
"Get a command to run.\n\n :returns:\n a list of strings representing a command to be passed to Popen.\n "
] |
Please provide a description of the function:def _main(environ, argv):
options = get_options(argv)
if options.version:
return handle_version()
vexrc = get_vexrc(options, environ)
# Handle --shell-config as soon as its arguments are available.
if options.shell_to_configure:
retur... | [
"Logic for main(), with less direct system interaction.\n\n Routines called here raise InvalidArgument with messages that\n should be delivered on stderr, to be caught by main.\n "
] |
Please provide a description of the function:def main():
argv = sys.argv[1:]
returncode = 1
try:
returncode = _main(os.environ, argv)
except exceptions.InvalidArgument as error:
if error.message:
sys.stderr.write("Error: " + error.message + '\n')
else:
... | [
"The main command-line entry point, with system interactions.\n "
] |
Please provide a description of the function:def get_processid(config):
pidfile = config.get('daemon', 'pidfile', fallback=None)
if pidfile is None:
raise ValueError("Configuration doesn't have pidfile option!")
try:
with open(pidfile, 'r') as _file:
pid = _file.read().rstr... | [
"Return process id of anycast-healthchecker.\n\n Arguments:\n config (obj): A configparser object with the configuration of\n anycast-healthchecker.\n\n Returns:\n The process id found in the pid file\n\n Raises:\n ValueError in the following cases\n - pidfile option is m... |
Please provide a description of the function:def parse_services(config, services):
enabled = 0
for service in services:
check_disabled = config.getboolean(service, 'check_disabled')
if not check_disabled:
enabled += 1
return enabled | [
"Parse configuration to return number of enabled service checks.\n\n Arguments:\n config (obj): A configparser object with the configuration of\n anycast-healthchecker.\n services (list): A list of section names which holds configuration\n for each service check\n\n Returns:\n ... |
Please provide a description of the function:def main():
arguments = docopt(__doc__)
config_file = '/etc/anycast-healthchecker.conf'
config_dir = '/etc/anycast-healthchecker.d'
config = configparser.ConfigParser()
config_files = [config_file]
config_files.extend(glob.glob(os.path.join(confi... | [
"Run check.\n\n anycast-healthchecker is a multi-threaded software and for each\n service check it holds a thread. If a thread dies then the service\n is not monitored anymore and the route for the IP associated with service\n it wont be withdrawn in case service goes down in the meantime.\n "
] |
Please provide a description of the function:def scary_path(path):
if not path:
return True
assert isinstance(path, bytes)
return not NOT_SCARY.match(path) | [
"Whitelist the WORKON_HOME strings we're willing to substitute in\n to strings that we provide for user's shell to evaluate.\n\n If it smells at all bad, return True.\n "
] |
Please provide a description of the function:def shell_config_for(shell, vexrc, environ):
here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(here, 'shell_configs', shell)
try:
with open(path, 'rb') as inp:
data = inp.read()
except FileNotFoundError as error:
... | [
"return completion config for the named shell.\n "
] |
Please provide a description of the function:def handle_shell_config(shell, vexrc, environ):
from vex import shell_config
data = shell_config.shell_config_for(shell, vexrc, environ)
if not data:
raise exceptions.OtherShell("unknown shell: {0!r}".format(shell))
if hasattr(sys.stdout, 'buffer... | [
"Carry out the logic of the --shell-config option.\n "
] |
Please provide a description of the function:def _run_check(self):
cmd = shlex.split(self.config['check_cmd'])
self.log.info("running %s", ' '.join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
start_time = ti... | [
"Execute a check command.\n\n Returns:\n True if the exit code of the command is 0 otherwise False.\n\n "
] |
Please provide a description of the function:def _ip_assigned(self):
output = []
cmd = [
'/sbin/ip',
'address',
'show',
'dev',
self.config['interface'],
'to',
self.ip_with_prefixlen,
]
if self.i... | [
"Check if IP prefix is assigned to loopback interface.\n\n Returns:\n True if IP prefix found assigned otherwise False.\n\n "
] |
Please provide a description of the function:def _check_disabled(self):
if self.config['check_disabled']:
if self.config['on_disabled'] == 'withdraw':
self.log.info("Check is disabled and ip_prefix will be "
"withdrawn")
self.log... | [
"Check if health check is disabled.\n\n It logs a message if health check is disabled and it also adds an item\n to the action queue based on 'on_disabled' setting.\n\n Returns:\n True if check is disabled otherwise False.\n\n "
] |
Please provide a description of the function:def run(self):
# Catch all possible exceptions raised by the running thread
# and let parent process know about it.
try:
self._run()
except Exception: # pylint: disable=broad-except
self.action.put(
... | [
"Wrap _run method."
] |
Please provide a description of the function:def _run(self):
up_cnt = 0
down_cnt = 0
# The current established state of the service check, it can be
# either UP or DOWN but only after a number of consecutive successful
# or unsuccessful health checks.
check_state... | [
"Discovers the health of a service.\n\n Runs until it is being killed from main program and is responsible to\n put an item into the queue based on the status of the health check.\n The status of service is consider UP after a number of consecutive\n successful health checks, in that cas... |
Please provide a description of the function:def main():
args = docopt(__doc__, version=__version__)
if args['--print']:
for section in DEFAULT_OPTIONS:
print("[{}]".format(section))
for key, value in DEFAULT_OPTIONS[section].items():
print("{k} = {v}".format... | [
"Parse CLI and starts main program."
] |
Please provide a description of the function:def get_environ(environ, defaults, ve_path):
# Copy the parent environment, add in defaults from .vexrc.
env = environ.copy()
env.update(defaults)
# Leaving in existing PYTHONHOME can cause some errors
if 'PYTHONHOME' in env:
del env['PYTHON... | [
"Make an environment to run with.\n "
] |
Please provide a description of the function:def run(command, env, cwd):
assert command
if cwd:
assert os.path.exists(cwd)
if platform.system() == "Windows":
exe = distutils.spawn.find_executable(command[0], path=env['PATH'])
if exe:
command[0] = exe
_, command_n... | [
"Run the given command.\n "
] |
Please provide a description of the function:def extract_key_value(line, environ):
segments = line.split("=", 1)
if len(segments) < 2:
return None
key, value = segments
# foo passes through as-is (with spaces stripped)
# '{foo}' passes through literally
# "{foo}" substitutes from en... | [
"Return key, value from given line if present, else return None.\n "
] |
Please provide a description of the function:def parse_vexrc(inp, environ):
heading = None
errors = []
with inp:
for line_number, line in enumerate(inp):
line = line.decode("utf-8")
if not line.strip():
continue
extracted_heading = extract_hea... | [
"Iterator yielding key/value pairs from given stream.\n\n yields tuples of heading, key, value.\n "
] |
Please provide a description of the function:def from_file(cls, path, environ):
instance = cls()
instance.read(path, environ)
return instance | [
"Make a Vexrc instance from given file in given environ.\n "
] |
Please provide a description of the function:def read(self, path, environ):
try:
inp = open(path, 'rb')
except FileNotFoundError as error:
if error.errno != 2:
raise
return None
parsing = parse_vexrc(inp, environ)
for heading, ... | [
"Read data from file into this vexrc instance.\n "
] |
Please provide a description of the function:def get_ve_base(self, environ):
# set ve_base to a path we can look for virtualenvs:
# 1. .vexrc
# 2. WORKON_HOME (as defined for virtualenvwrapper's benefit)
# 3. $HOME/.virtualenvs
# (unless we got --path, then we don't need... | [
"Find a directory to look for virtualenvs in.\n "
] |
Please provide a description of the function:def get_shell(self, environ):
command = self.headings[self.default_heading].get('shell')
if not command and os.name != 'nt':
command = environ.get('SHELL', '')
command = shlex.split(command) if command else None
return com... | [
"Find a command to run.\n "
] |
Please provide a description of the function:def files(self):
info = self.metainfo['info']
if 'length' in info: # Singlefile
yield info['name']
elif 'files' in info: # Multifile torrent
rootdir = self.name
for fileinfo in info['files']:
... | [
"\n Yield relative file paths specified in :attr:`metainfo`\n\n Each paths starts with :attr:`name`.\n\n Note that the paths may not exist. See :attr:`filepaths` for existing\n files.\n "
] |
Please provide a description of the function:def filepaths(self):
if self.path is not None:
yield from utils.filepaths(self.path, exclude=self.exclude,
hidden=False, empty=False) | [
"\n Yield absolute paths to existing files in :attr:`path`\n\n Any files that match patterns in :attr:`exclude` as well as hidden and\n empty files are not included.\n "
] |
Please provide a description of the function:def filetree(self):
tree = {} # Complete directory tree
prefix = []
paths = (f.split(os.sep) for f in self.files)
for path in paths:
dirpath = path[:-1] # Path without filename
filename = path[-1]
... | [
"\n :attr:`files` as a dictionary tree\n\n Each node is a ``dict`` that maps directory/file names to child nodes.\n Each child node is a ``dict`` for directories and ``None`` for files.\n\n If :attr:`path` is ``None``, this is an empty ``dict``.\n "
] |
Please provide a description of the function:def size(self):
if 'length' in self.metainfo['info']: # Singlefile
return self.metainfo['info']['length']
elif 'files' in self.metainfo['info']: # Multifile torrent
return sum(fileinfo['length']
for f... | [
"\n Total size of content in bytes or ``None`` if :attr:`path` is ``None``\n "
] |
Please provide a description of the function:def piece_size(self):
if 'piece length' not in self.metainfo['info']:
if self.size is None:
return None
else:
self.calculate_piece_size()
return self.metainfo['info']['piece length'] | [
"\n Piece size/length or ``None``\n\n If set to ``None``, :attr:`calculate_piece_size` is called.\n\n If :attr:`size` returns ``None``, this also returns ``None``.\n\n Setting this property sets ``piece length`` in :attr:`metainfo`\\\n ``['info']``.\n "
] |
Please provide a description of the function:def calculate_piece_size(self):
size = self.size
if not size:
raise RuntimeError(f'Cannot calculate piece size with no "path" specified')
else:
self.metainfo['info']['piece length'] = utils.calc_piece_size(
... | [
"\n Calculate and add ``piece length`` to ``info`` in :attr:`metainfo`\n\n The piece size is calculated so that there are no more than\n :attr:`MAX_PIECES` pieces unless it is larger than\n :attr:`MAX_PIECE_SIZE`, in which case there is no limit on the number of\n pieces.\n\n ... |
Please provide a description of the function:def pieces(self):
if self.piece_size is None:
return None
else:
return math.ceil(self.size / self.piece_size) | [
"\n Number of pieces the content is split into or ``None`` if :attr:`piece_size`\n returns ``None``\n "
] |
Please provide a description of the function:def name(self):
if 'name' not in self.metainfo['info'] and self.path is not None:
self.metainfo['info']['name'] = os.path.basename(self.path)
return self.metainfo['info'].get('name', None) | [
"\n Name of the torrent\n\n Default to last item in :attr:`path` or ``None`` if :attr:`path` is\n ``None``.\n\n Setting this property sets or removes ``name`` in :attr:`metainfo`\\\n ``['info']``.\n "
] |
Please provide a description of the function:def trackers(self):
announce_list = self.metainfo.get('announce-list', None)
if not announce_list:
announce = self.metainfo.get('announce', None)
if announce:
return [[announce]]
else:
retur... | [
"\n List of tiers of announce URLs or ``None`` for no trackers\n\n A tier is either a single announce URL (:class:`str`) or an\n :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce\n URLs.\n\n Setting this property sets or removes ``announce`` and ``announce-list``... |
Please provide a description of the function:def infohash(self):
self.validate()
info = self.convert()[b'info']
return sha1(bencode(info)).hexdigest() | [
"SHA1 info hash"
] |
Please provide a description of the function:def infohash_base32(self):
self.validate()
info = self.convert()[b'info']
return b32encode(sha1(bencode(info)).digest()) | [
"Base32 encoded SHA1 info hash"
] |
Please provide a description of the function:def generate(self, callback=None, interval=0):
if self.path is None:
raise RuntimeError('generate() called with no path specified')
elif self.size <= 0:
raise error.PathEmptyError(self.path)
elif not os.path.exists(sel... | [
"\n Hash pieces and report progress to `callback`\n\n This method sets ``pieces`` in :attr:`metainfo`\\ ``['info']`` when all\n pieces are hashed successfully.\n\n :param callable callback: Callable with signature ``(torrent, filepath,\n pieces_done, pieces_total)``; if `callb... |
Please provide a description of the function:def convert(self):
try:
return utils.encode_dict(self.metainfo)
except ValueError as e:
raise error.MetainfoError(str(e)) | [
"\n Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all\n values encoded to :class:`bytes`, :class:`int`, :class:`list` or\n :class:`OrderedDict`\n\n :raises MetainfoError: on values that cannot be converted properly\n "
] |
Please provide a description of the function:def validate(self):
md = self.metainfo
info = md['info']
# Check values shared by singlefile and multifile torrents
utils.assert_type(md, ('info', 'name'), (str,), must_exist=True)
utils.assert_type(md, ('info', 'piece length... | [
"\n Check if all mandatory keys exist in :attr:`metainfo` and are of expected\n types\n\n The necessary values are documented here:\n | http://bittorrent.org/beps/bep_0003.html\n | https://wiki.theory.org/index.php/BitTorrentSpecification#Metainfo_File_Structure\n\n ... |
Please provide a description of the function:def dump(self, validate=True):
if validate:
self.validate()
return bencode(self.convert()) | [
"\n Create bencoded :attr:`metainfo` (i.e. the content of a torrent file)\n\n :param bool validate: Whether to run :meth:`validate` first\n\n :return: :attr:`metainfo` as bencoded :class:`bytes`\n "
] |
Please provide a description of the function:def write_stream(self, stream, validate=True):
content = self.dump(validate=validate)
try:
# Remove existing data from stream *after* dump() didn't raise
# anything so we don't destroy it prematurely.
if stream.see... | [
"\n Write :attr:`metainfo` to a file-like object\n\n Before any data is written, `stream` is truncated if possible.\n\n :param stream: Writable file-like object (e.g. :class:`io.BytesIO`)\n :param bool validate: Whether to run :meth:`validate` first\n\n :raises WriteError: if writ... |
Please provide a description of the function:def write(self, filepath, validate=True, overwrite=False, mode=0o666):
if not overwrite and os.path.exists(filepath):
raise error.WriteError(errno.EEXIST, filepath)
# Get file content before opening the file in case there are errors like... | [
"\n Write :attr:`metainfo` to torrent file\n\n This method is essentially equivalent to:\n\n >>> with open('my.torrent', 'wb') as f:\n ... f.write(torrent.dump())\n\n :param filepath: Path of the torrent file\n :param bool validate: Whether to run :meth:`validate` first... |
Please provide a description of the function:def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True):
if validate:
self.validate()
parts = [f'xt=urn:btih:{self.infohash}']
if name:
parts.append(f'dn={utils.urlquote(self.name)}')
... | [
"\n BTIH Magnet URI\n\n :param bool name: Whether to include the name\n :param bool size: Whether to include the size\n :param bool trackers: Whether to include all trackers\n :param bool tracker: Whether to include only the first tracker of the\n first tier (overrides ... |
Please provide a description of the function:def read_stream(cls, stream, validate=True):
try:
content = stream.read(cls.MAX_TORRENT_FILE_SIZE)
except OSError as e:
raise error.ReadError(e.errno)
else:
try:
metainfo_enc = bdecode(conte... | [
"\n Read torrent metainfo from file-like object\n\n :param stream: Readable file-like object (e.g. :class:`io.BytesIO`)\n :param bool validate: Whether to run :meth:`validate` on the new Torrent\n object\n\n :raises ReadError: if reading from `stream` fails\n :raises Pa... |
Please provide a description of the function:def read(cls, filepath, validate=True):
try:
with open(filepath, 'rb') as fh:
return cls.read_stream(fh)
except (OSError, error.ReadError) as e:
raise error.ReadError(e.errno, filepath)
except error.Par... | [
"\n Read torrent metainfo from file\n\n :param filepath: Path of the torrent file\n :param bool validate: Whether to run :meth:`validate` on the new Torrent\n object\n\n :raises ReadError: if reading from `filepath` fails\n :raises ParseError: if `filepath` does not con... |
Please provide a description of the function:def copy(self):
from copy import deepcopy
cp = type(self)()
cp._metainfo = deepcopy(self._metainfo)
return cp | [
"\n Return a new object with the same metainfo\n\n Internally, this simply copies the internal metainfo dictionary with\n :func:`copy.deepcopy` and gives it to the new instance.\n "
] |
Please provide a description of the function:def validated_url(url):
try:
u = urlparse(url)
u.port # Trigger 'invalid port' exception
except Exception:
raise error.URLError(url)
else:
if not u.scheme or not u.netloc:
raise error.URLError(url)
return ... | [
"Return url if valid, raise URLError otherwise"
] |
Please provide a description of the function:def read_chunks(filepath, chunk_size):
try:
with open(filepath, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if chunk:
yield chunk
else:
break # EOF
... | [
"Generator that yields chunks from file"
] |
Please provide a description of the function:def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size):
ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2)))
if ps < min_piece_size:
ps = min_piece_size
if ps > max_piece_size:
ps = max_piece_size
return ... | [
"Calculate piece size"
] |
Please provide a description of the function:def is_power_of_2(num):
log = math.log2(num)
return int(log) == float(log) | [
"Return whether `num` is a power of two"
] |
Please provide a description of the function:def is_hidden(path):
for name in path.split(os.sep):
if name != '.' and name != '..' and name and name[0] == '.':
return True
return False | [
"Whether file or directory is hidden"
] |
Please provide a description of the function:def filepaths(path, exclude=(), hidden=True, empty=True):
if not os.path.exists(path):
raise error.PathNotFoundError(path)
elif not os.access(path, os.R_OK,
effective_ids=os.access in os.supports_effective_ids):
raise error... | [
"\n Return list of absolute, sorted file paths\n\n path: Path to file or directory\n exclude: List of file name patterns to exclude\n hidden: Whether to include hidden files\n empty: Whether to include empty files\n\n Raise PathNotFoundError if path doesn't exist.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.