INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
r Log _message. format ( * args ** kwargs ) with severity _level. | def log(_self, _level, _message, *args, **kwargs):
r"""Log ``_message.format(*args, **kwargs)`` with severity ``_level``."""
logger = _self.opt(
exception=_self._exception,
record=_self._record,
lazy=_self._lazy,
ansi=_self._ansi,
raw=_self._ra... |
Deprecated function to |add| a new handler. | def start(self, *args, **kwargs):
"""Deprecated function to |add| a new handler.
Warnings
--------
.. deprecated:: 0.2.2
``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less
confusing name.
"""
warnings.warn(
... |
Deprecated function to |remove| an existing handler. | def stop(self, *args, **kwargs):
"""Deprecated function to |remove| an existing handler.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name.
"""
warnings.wa... |
Converts a django rest frameworks field to a graphql field and marks the field as required if we are creating an input type and the field itself is required | def convert_serializer_field(field, is_input=True):
"""
Converts a django rest frameworks field to a graphql field
and marks the field as required if we are creating an input type
and the field itself is required
"""
graphql_type = get_graphene_type_from_serializer_field(field)
args = []
... |
If the given setting is a string import notation then perform the necessary import or imports. | def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None
elif isinstance(val, six.string_types):
return import_from_string(val, setting_name)
elif isinstance(val,... |
Create a filterset for the given model using the provided meta data | def custom_filterset_factory(model, filterset_base_class=FilterSet, **meta):
""" Create a filterset for the given model using the provided meta data
"""
meta.update({"model": model})
meta_class = type(str("Meta"), (object,), meta)
filterset = type(
str("%sFilterSet" % model._meta.object_name... |
Convert the filter value to a primary key before filtering | def filter(self, qs, value):
""" Convert the filter value to a primary key before filtering """
_id = None
if value is not None:
_, _id = from_global_id(value)
return super(GlobalIDFilter, self).filter(qs, _id) |
Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL | def get_filtering_args_from_filterset(filterset_class, type):
""" Inspect a FilterSet and produce the arguments to pass to
a Graphene Field. These arguments will be available to
filter against in the GraphQL
"""
from ..forms.converter import convert_form_field
args = {}
for name, fi... |
Map per - topic results to per - topic futures in futmap. The result value of each ( successful ) future is None. | def _make_topics_result(f, futmap):
"""
Map per-topic results to per-topic futures in futmap.
The result value of each (successful) future is None.
"""
try:
result = f.result()
for topic, error in result.items():
fut = futmap.get(topic, Non... |
Map per - resource results to per - resource futures in futmap. The result value of each ( successful ) future is a ConfigResource. | def _make_resource_result(f, futmap):
"""
Map per-resource results to per-resource futures in futmap.
The result value of each (successful) future is a ConfigResource.
"""
try:
result = f.result()
for resource, configs in result.items():
fu... |
Create futures and a futuremap for the keys in futmap_keys and create a request - level future to be bassed to the C API. | def _make_futures(futmap_keys, class_check, make_result_fn):
"""
Create futures and a futuremap for the keys in futmap_keys,
and create a request-level future to be bassed to the C API.
"""
futmap = {}
for key in futmap_keys:
if class_check is not None and not... |
Create new topics in cluster. | def create_topics(self, new_topics, **kwargs):
"""
Create new topics in cluster.
The future result() value is None.
:param list(NewTopic) new_topics: New topics to be created.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlli... |
Delete topics. | def delete_topics(self, topics, **kwargs):
"""
Delete topics.
The future result() value is None.
:param list(str) topics: Topics to mark for deletion.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlling how long the DeleteTop... |
Create additional partitions for the given topics. | def create_partitions(self, new_partitions, **kwargs):
"""
Create additional partitions for the given topics.
The future result() value is None.
:param list(NewPartitions) new_partitions: New partitions to be created.
:param float operation_timeout: Set broker's operation timeo... |
Get configuration for the specified resources. | def describe_configs(self, resources, **kwargs):
"""
Get configuration for the specified resources.
The future result() value is a dict(<configname, ConfigEntry>).
:warning: Multiple resources and resource types may be requested,
but at most one resource of type RESOU... |
Parse a schema given a schema string | def loads(schema_str):
""" Parse a schema given a schema string """
try:
if sys.version_info[0] < 3:
return schema.parse(schema_str)
else:
return schema.Parse(schema_str)
except schema.SchemaParseException as e:
raise ClientError("Schema parse failed: %s" % (s... |
Asynchronously sends message to Kafka by encoding with specified or default avro schema. | def produce(self, **kwargs):
"""
Asynchronously sends message to Kafka by encoding with specified or default avro schema.
:param str topic: topic name
:param object value: An object to serialize
:param str value_schema: Avro schema for value
:param ob... |
This is an overriden method from confluent_kafka. Consumer class. This handles message deserialization using avro schema | def poll(self, timeout=None):
"""
This is an overriden method from confluent_kafka.Consumer class. This handles message
deserialization using avro schema
:param float timeout: Poll timeout in seconds (default: indefinite)
:returns: message object with deserialized key and value ... |
Given a parsed avro schema encode a record for the given topic. The record is expected to be a dictionary. | def encode_record_with_schema(self, topic, schema, record, is_key=False):
"""
Given a parsed avro schema, encode a record for the given topic. The
record is expected to be a dictionary.
The schema is registered with the subject of 'topic-value'
:param str topic: Topic name
... |
Encode a record with a given schema id. The record must be a python dictionary.: param int schema_id: integer ID: param dict record: An object to serialize: param bool is_key: If the record is a key: returns: decoder function: rtype: func | def encode_record_with_schema_id(self, schema_id, record, is_key=False):
"""
Encode a record with a given schema id. The record must
be a python dictionary.
:param int schema_id: integer ID
:param dict record: An object to serialize
:param bool is_key: If the record is a... |
Decode a message from kafka that has been encoded for use with the schema registry.: param str|bytes or None message: message key or value to be decoded: returns: Decoded message contents.: rtype dict: | def decode_message(self, message, is_key=False):
"""
Decode a message from kafka that has been encoded for use with
the schema registry.
:param str|bytes or None message: message key or value to be decoded
:returns: Decoded message contents.
:rtype dict:
"""
... |
Delivery report callback called ( from flush () ) on successful or failed delivery of the message. | def acked(err, msg):
"""Delivery report callback called (from flush()) on successful or failed delivery of the message."""
if err is not None:
print("failed to deliver message: {}".format(err.str()))
else:
print("produced to: {} [{}] @ {}".format(msg.topic(), msg.partition(), msg.offset())) |
Create topics | def example_create_topics(a, topics):
""" Create topics """
new_topics = [NewTopic(topic, num_partitions=3, replication_factor=1) for topic in topics]
# Call create_topics to asynchronously create topics, a dict
# of <topic,future> is returned.
fs = a.create_topics(new_topics)
# Wait for opera... |
delete topics | def example_delete_topics(a, topics):
""" delete topics """
# Call delete_topics to asynchronously delete topics, a future is returned.
# By default this operation on the broker returns immediately while
# topics are deleted in the background. But here we give it some time (30s)
# to propagate in t... |
create partitions | def example_create_partitions(a, topics):
""" create partitions """
new_parts = [NewPartitions(topic, int(new_total_count)) for
topic, new_total_count in zip(topics[0::2], topics[1::2])]
# Try switching validate_only to True to only validate the operation
# on the broker but not actua... |
describe configs | def example_describe_configs(a, args):
""" describe configs """
resources = [ConfigResource(restype, resname) for
restype, resname in zip(args[0::2], args[1::2])]
fs = a.describe_configs(resources)
# Wait for operation to finish.
for res, f in fs.items():
try:
... |
Alter configs atomically replacing non - specified configuration properties with their default values. | def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with their default values.
"""
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
reso... |
The AlterConfigs Kafka API requires all configuration to be passed any left out configuration properties will revert to their default settings. | def example_delta_alter_configs(a, args):
"""
The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the configuration ... |
list topics and cluster metadata | def example_list(a, args):
""" list topics and cluster metadata """
if len(args) == 0:
what = "all"
else:
what = args[0]
md = a.list_topics(timeout=10)
print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name))
if what in ("all", "broke... |
Resolve embedded plugins from the wheel s library directory. | def _resolve_plugins(plugins):
""" Resolve embedded plugins from the wheel's library directory.
For internal module use only.
:param str plugins: The plugin.library.paths value
"""
import os
from sys import platform
# Location of __init__.py and the embedded library directory
... |
Handle delivery reports served from producer. poll. This callback takes an extra argument obj. This allows the original contents to be included for debugging purposes. | def on_delivery(err, msg, obj):
"""
Handle delivery reports served from producer.poll.
This callback takes an extra argument, obj.
This allows the original contents to be included for debugging purposes.
"""
if err is not None:
print('Message {} delivery failed for user {} wi... |
Produce User records | def produce(topic, conf):
"""
Produce User records
"""
from confluent_kafka.avro import AvroProducer
producer = AvroProducer(conf, default_value_schema=record_schema)
print("Producing user records to topic {}. ^c to exit.".format(topic))
while True:
# Instantiate new User, pop... |
Consume User records | def consume(topic, conf):
"""
Consume User records
"""
from confluent_kafka.avro import AvroConsumer
from confluent_kafka.avro.serializer import SerializerError
print("Consuming user records from topic {} with group {}. ^c to exit.".format(topic, conf["group.id"]))
c = AvroConsumer(con... |
POST/ subjects/ ( string: subject )/ versions Register a schema with the registry under the given subject and receive a schema id. | def register(self, subject, avro_schema):
"""
POST /subjects/(string: subject)/versions
Register a schema with the registry under the given subject
and receive a schema id.
avro_schema must be a parsed schema from the python avro library
Multiple instances of the same s... |
DELETE/ subjects/ ( string: subject ) Deletes the specified subject and its associated compatibility level if registered. It is recommended to use this API only when a topic needs to be recycled or in development environments.: param subject: subject name: returns: version of the schema deleted under this subject: rtyp... | def delete_subject(self, subject):
"""
DELETE /subjects/(string: subject)
Deletes the specified subject and its associated compatibility level if registered.
It is recommended to use this API only when a topic needs to be recycled or in development environments.
:param subject: s... |
GET/ schemas/ ids/ { int: id } Retrieve a parsed avro schema by id or None if not found: param int schema_id: int value: returns: Avro schema: rtype: schema | def get_by_id(self, schema_id):
"""
GET /schemas/ids/{int: id}
Retrieve a parsed avro schema by id or None if not found
:param int schema_id: int value
:returns: Avro schema
:rtype: schema
"""
if schema_id in self.id_to_schema:
return self.id_t... |
POST/ subjects/ ( string: subject ) | def get_version(self, subject, avro_schema):
"""
POST /subjects/(string: subject)
Get the version of a schema for a given subject.
Returns None if not found.
:param str subject: subject name
:param: schema avro_schema: Avro schema
:returns: version
:rtyp... |
PUT/ config/ ( string: subject ) | def update_compatibility(self, level, subject=None):
"""
PUT /config/(string: subject)
Update the compatibility level for a subject. Level must be one of:
:param str level: ex: 'NONE','FULL','FORWARD', or 'BACKWARD'
"""
if level not in VALID_LEVELS:
raise C... |
GET/ config Get the current compatibility level for a subject. Result will be one of: | def get_compatibility(self, subject=None):
"""
GET /config
Get the current compatibility level for a subject. Result will be one of:
:param str subject: subject name
:raises ClientError: if the request was unsuccessful or an invalid compatibility level was returned
:ret... |
Download artifact from S3 and store in dirpath directory. If the artifact is already downloaded nothing is done. | def download(self, dirpath):
""" Download artifact from S3 and store in dirpath directory.
If the artifact is already downloaded nothing is done. """
if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0:
return
print('Downloading %s -> %s' % (self.path, self.... |
Collect single S3 artifact: param: path string: S3 path | def collect_single_s3(self, path):
""" Collect single S3 artifact
:param: path string: S3 path
"""
# The S3 folder contains the tokens needed to perform
# matching of project, gitref, etc.
folder = os.path.dirname(path)
rinfo = re.findall(r'(?P<tag>[^-]+)-(?P<v... |
Collect and download build - artifacts from S3 based on git reference | def collect_s3(self):
""" Collect and download build-artifacts from S3 based on git reference """
print('Collecting artifacts matching tag/sha %s from S3 bucket %s' % (self.gitref, s3_bucket))
self.s3 = boto3.resource('s3')
self.s3_bucket = self.s3.Bucket(s3_bucket)
self.s3.meta.... |
Collect artifacts from a local directory possibly previously collected from s3 | def collect_local(self, path):
""" Collect artifacts from a local directory possibly previously
collected from s3 """
for f in os.listdir(path):
lpath = os.path.join(path, f)
if not os.path.isfile(lpath):
continue
Artifact(self, lpath) |
Return a value for name from command line args then config file options. Specify key if the config file option is not the same as name. | def _config(name, key=None, **kwargs):
'''
Return a value for 'name' from command line args then config file options.
Specify 'key' if the config file option is not the same as 'name'.
'''
if key is None:
key = name
if name in kwargs:
value = kwargs[name]
else:
value ... |
Add replace or update the A and PTR ( reverse ) records for a host. | def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True,
timeout=5, port=53, **kwargs):
'''
Add, replace, or update the A and PTR (reverse) records for a host.
CLI Example:
.. code-block:: bash
salt ns1 ddns.add_host example.com host1 60 10.1.1.1
'''
res = ... |
Delete the forward and reverse records for a host. | def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53,
**kwargs):
'''
Delete the forward and reverse records for a host.
Returns true if any records are deleted.
CLI Example:
.. code-block:: bash
salt ns1 ddns.delete_host example.com host1
'''
fqd... |
Add replace or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true first deletes all records for this name and type. | def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5,
replace=False, port=53, **kwargs):
'''
Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, fir... |
Set all Ansible modules callables: return: | def _set_callables(modules):
'''
Set all Ansible modules callables
:return:
'''
def _set_function(cmd_name, doc):
'''
Create a Salt function for the Ansible module.
'''
def _cmd(*args, **kw):
'''
Call an Ansible module as a function from the Sa... |
Display help on Ansible standard module. | def help(module=None, *args):
'''
Display help on Ansible standard module.
:param module:
:return:
'''
if not module:
raise CommandExecutionError('Please tell me what module you want to have helped with. '
'Or call "ansible.list" to know what is avail... |
Run Ansible Playbooks | def playbooks(playbook, rundir=None, check=False, diff=False, extra_vars=None,
flush_cache=False, forks=5, inventory=None, limit=None,
list_hosts=False, list_tags=False, list_tasks=False,
module_path=None, skip_tags=None, start_at_task=None,
syntax_check=False, ta... |
Get installed Ansible modules: return: | def _get_modules_map(self, path=None):
'''
Get installed Ansible modules
:return:
'''
paths = {}
root = ansible.modules.__path__[0]
if not path:
path = root
for p_el in os.listdir(path):
p_el_path = os.path.join(path, p_el)
... |
Introspect Ansible module. | def load_module(self, module):
'''
Introspect Ansible module.
:param module:
:return:
'''
m_ref = self._modules_map.get(module)
if m_ref is None:
raise LoaderError('Module "{0}" was not found'.format(module))
mod = importlib.import_module('ans... |
Return module map references.: return: | def get_modules_list(self, pattern=None):
'''
Return module map references.
:return:
'''
if pattern and '*' not in pattern:
pattern = '*{0}*'.format(pattern)
modules = []
for m_name, m_path in self._modules_map.items():
m_path = m_path.spli... |
Call an Ansible module by invoking it.: param module: the name of the module.: param args: Arguments to the module: param kwargs: keywords to the module: return: | def call(self, module, *args, **kwargs):
'''
Call an Ansible module by invoking it.
:param module: the name of the module.
:param args: Arguments to the module
:param kwargs: keywords to the module
:return:
'''
module = self._resolver.load_module(module)
... |
Clean out a template temp file | def __clean_tmp(sfn):
'''
Clean out a template temp file
'''
if sfn.startswith(os.path.join(tempfile.gettempdir(),
salt.utils.files.TEMPFILE_PREFIX)):
# Don't remove if it exists in file_roots (any saltenv)
all_roots = itertools.chain.from_iterable(
... |
This function does NOT do any diffing it just checks the old and new files to see if either is binary and provides an appropriate string noting the difference between the two files. If neither file is binary an empty string is returned. | def _binary_replace(old, new):
'''
This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should... |
Returns a list of the lines in the string breaking at line boundaries and preserving a trailing newline ( if present ). | def _splitlines_preserving_trailing_newline(str):
'''
Returns a list of the lines in the string, breaking at line boundaries and
preserving a trailing newline (if present).
Essentially, this works like ``str.striplines(False)`` but preserves an
empty line at the end. This is equivalent to the follo... |
Convert the group id to the group name on this system | def gid_to_group(gid):
'''
Convert the group id to the group name on this system
gid
gid to convert to a group name
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group 0
'''
try:
gid = int(gid)
except ValueError:
# This is not an integer, mayb... |
Convert the group to the gid on this system | def group_to_gid(group):
'''
Convert the group to the gid on this system
group
group to convert to its gid
CLI Example:
.. code-block:: bash
salt '*' file.group_to_gid root
'''
if group is None:
return ''
try:
if isinstance(group, int):
ret... |
Return the id of the group that owns a given file | def get_gid(path, follow_symlinks=True):
'''
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_gid /etc/passwd... |
Return the group that owns a given file | def get_group(path, follow_symlinks=True):
'''
Return the group that owns a given file
path
file or directory of which to get the group
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_group /etc/passwd
... |
Convert user name to a uid | def user_to_uid(user):
'''
Convert user name to a uid
user
user name to convert to its uid
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid root
'''
if user is None:
user = salt.utils.user.get_user()
try:
if isinstance(user, int):
... |
Return the id of the user that owns a given file | def get_uid(path, follow_symlinks=True):
'''
Return the id of the user that owns a given file
path
file or directory of which to get the uid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_uid /etc/passwd
... |
Return the mode of a file | def get_mode(path, follow_symlinks=True):
'''
Return the mode of a file
path
file or directory of which to get the mode
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
.. versionchange... |
Set the mode of a file | def set_mode(path, mode):
'''
Set the mode of a file
path
file or directory of which to set the mode
mode
mode to set the path to
CLI Example:
.. code-block:: bash
salt '*' file.set_mode /etc/passwd 0644
'''
path = os.path.expanduser(path)
mode = six.tex... |
Chown a file pass the file the desired user and group without following symlinks. | def lchown(path, user, group):
'''
Chown a file, pass the file the desired user and group without following
symlinks.
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/pass... |
Chown a file pass the file the desired user and group | def chown(path, user, group):
'''
Chown a file, pass the file the desired user and group
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/passwd root root
'''
path = o... |
Change the group of a file | def chgrp(path, group):
'''
Change the group of a file
path
path to the file or directory
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chgrp /etc/passwd root
'''
path = os.path.expanduser(path)
user = get_user(path)
return chown(... |
.. versionadded:: 2018. 3. 0 | def _cmp_attrs(path, attrs):
'''
.. versionadded:: 2018.3.0
Compare attributes of a given file to given attributes.
Returns a pair (list) where first item are attributes to
add and second item are to be removed.
Please take into account when using this function that some minions will
not h... |
.. versionadded:: 2018. 3. 0.. versionchanged:: 2018. 3. 1 If lsattr is not installed on the system None is returned... versionchanged:: 2018. 3. 4 If on AIX None is returned even if in filesystem as lsattr on AIX is not the same thing as the linux version. | def lsattr(path):
'''
.. versionadded:: 2018.3.0
.. versionchanged:: 2018.3.1
If ``lsattr`` is not installed on the system, ``None`` is returned.
.. versionchanged:: 2018.3.4
If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX``
is not the same thing as t... |
.. versionadded:: 2018. 3. 0 | def chattr(*files, **kwargs):
'''
.. versionadded:: 2018.3.0
Change the attributes of files. This function accepts one or more files and
the following options:
operator
Can be wither ``add`` or ``remove``. Determines whether attributes
should be added or removed from files
att... |
Return the checksum for the given file. The following checksum algorithms are supported: | def get_sum(path, form='sha256'):
'''
Return the checksum for the given file. The following checksum algorithms
are supported:
* md5
* sha1
* sha224
* sha256 **(default)**
* sha384
* sha512
path
path to the file or directory
form
desired sum format
CLI... |
Get the hash sum of a file | def get_hash(path, form='sha256', chunk_size=65536):
'''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really ... |
.. versionadded:: 2016. 11. 0 | def get_source_sum(file_name='',
source='',
source_hash=None,
source_hash_name=None,
saltenv='base'):
'''
.. versionadded:: 2016.11.0
Used by :py:func:`file.get_managed <salt.modules.file.get_managed>` to
obtain the hash and ha... |
Check if a file matches the given hash string | def check_hash(path, file_hash):
'''
Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versioncha... |
Approximate the Unix find ( 1 ) command and return a list of paths that meet the specified criteria. | def find(path, *args, **kwargs):
'''
Approximate the Unix ``find(1)`` command and return a list of paths that
meet the specified criteria.
The options include match criteria:
.. code-block:: text
name = path-glob # case sensitive
iname = path-glob ... |
Escape single quotes and forward slashes | def _sed_esc(string, escape_all=False):
'''
Escape single quotes and forward slashes
'''
special_chars = "^.[$()|*+?{"
string = string.replace("'", "'\"'\"'").replace("/", "\\/")
if escape_all is True:
for char in special_chars:
string = string.replace(char, "\\" + char)
... |
.. deprecated:: 0. 17. 0 Use: py: func: ~salt. modules. file. replace instead. | def sed(path,
before,
after,
limit='',
backup='.bak',
options='-r -e',
flags='g',
escape_all=False,
negate_match=False):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Make a simple edit to a file
Equ... |
.. deprecated:: 0. 17. 0 Use: func: search instead. | def sed_contains(path,
text,
limit='',
flags='g'):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the file at ``path`` contains ``text``. Utilizes sed to
perform the search (line-wise search).
Note: the ``p`` flag wil... |
.. deprecated:: 0. 17. 0 Use: py: func: ~salt. modules. file. replace instead. | def psed(path,
before,
after,
limit='',
backup='.bak',
flags='gMS',
escape_all=False,
multi=False):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Make a simple edit to a file (pure Python version)
Equ... |
Does the actual work for file. psed so that single lines can be passed in | def _psed(text,
before,
after,
limit,
flags):
'''
Does the actual work for file.psed, so that single lines can be passed in
'''
atext = text
if limit:
limit = re.compile(limit)
comps = text.split(limit)
atext = ''.join(comps[1:])
c... |
.. deprecated:: 0. 17. 0 Use: py: func: ~salt. modules. file. replace instead. | def uncomment(path,
regex,
char='#',
backup='.bak'):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Uncomment specified commented lines in a file
path
The full path to the file to be edited
regex
A regu... |
.. deprecated:: 0. 17. 0 Use: py: func: ~salt. modules. file. replace instead. | def comment(path,
regex,
char='#',
backup='.bak'):
'''
.. deprecated:: 0.17.0
Use :py:func:`~salt.modules.file.replace` instead.
Comment out specified lines in a file
path
The full path to the file to be edited
regex
A regular expression u... |
r Comment or Uncomment a line in a text file. | def comment_line(path,
regex,
char='#',
cmnt=True,
backup='.bak'):
r'''
Comment or Uncomment a line in a text file.
:param path: string
The full path to the text file.
:param regex: string
A regex expression that begin... |
Return an integer appropriate for use as a flag for the re module from a list of human - readable strings | def _get_flags(flags):
'''
Return an integer appropriate for use as a flag for the re module from a
list of human-readable strings
.. code-block:: python
>>> _get_flags(['MULTILINE', 'IGNORECASE'])
10
>>> _get_flags('MULTILINE')
8
>>> _get_flags(2)
2
... |
Combine flags and new_flags | def _add_flags(flags, new_flags):
'''
Combine ``flags`` and ``new_flags``
'''
flags = _get_flags(flags)
new_flags = _get_flags(new_flags)
return flags | new_flags |
Create a temp file and move/ copy the contents of path to the temp file. Return the path to the temp file. | def _mkstemp_copy(path,
preserve_inode=True):
'''
Create a temp file and move/copy the contents of ``path`` to the temp file.
Return the path to the temp file.
path
The full path to the file whose contents will be moved/copied to a temp file.
Whether it's moved or copi... |
Returns True if src and probe at least matches at the beginning till some point. | def _starts_till(src, probe, strip_comments=True):
'''
Returns True if src and probe at least matches at the beginning till some point.
'''
def _strip_comments(txt):
'''
Strip possible comments.
Usually comments are one or two symbols at the beginning of the line, separated with ... |
Expand regular expression to static match. | def _regex_to_static(src, regex):
'''
Expand regular expression to static match.
'''
if not src or not regex:
return None
try:
compiled = re.compile(regex, re.DOTALL)
src = [line for line in src if compiled.search(line) or line.count(regex)]
except Exception as ex:
... |
Raise an exception if there are different amount of specified occurrences in src. | def _assert_occurrence(probe, target, amount=1):
'''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = len(probe)
if occ > amount:
msg = 'more than'
elif occ < amount:
msg = 'less than'
elif not occ:
msg = 'no'
else:
... |
Indent the line with the source line. | def _set_line_indent(src, line, indent):
'''
Indent the line with the source line.
'''
if not indent:
return line
idt = []
for c in src:
if c not in ['\t', ' ']:
break
idt.append(c)
return ''.join(idt) + line.lstrip() |
Add line ending | def _set_line_eol(src, line):
'''
Add line ending
'''
line_ending = _get_eol(src) or os.linesep
return line.rstrip() + line_ending |
.. versionadded:: 2015. 8. 0 | def line(path, content=None, match=None, mode=None, location=None,
before=None, after=None, show_changes=True, backup=False,
quiet=False, indent=True):
'''
.. versionadded:: 2015.8.0
Edit a line in the configuration file. The ``path`` and ``content``
arguments are required, as well as... |
.. versionadded:: 0. 17. 0 | def replace(path,
pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
backup='.bak',
dry_run=False,
search_only=False... |
.. versionadded:: 2014. 1. 0 | def blockreplace(path,
marker_start='#-- start managed zone --',
marker_end='#-- end managed zone --',
content='',
append_if_not_found=False,
prepend_if_not_found=False,
backup='.bak',
dry_run=False,
show_changes=True,
append_newline=False,
... |
.. versionadded:: 0. 17. 0 | def search(path,
pattern,
flags=8,
bufsize=1,
ignore_if_missing=False,
multiline=False
):
'''
.. versionadded:: 0.17.0
Search for occurrences of a pattern in a file
Except for multiline, params are identical to
:py:func:`~salt.modules.file.replace`.
... |
.. versionadded:: 0. 10. 4 | def patch(originalfile, patchfile, options='', dry_run=False):
'''
.. versionadded:: 0.10.4
Apply a patch to a file or directory.
Equivalent to:
.. code-block:: bash
patch <options> -i <patchfile> <originalfile>
Or, when a directory is patched:
.. code-block:: bash
pat... |
.. deprecated:: 0. 17. 0 Use: func: search instead. | def contains(path, text):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return ``True`` if the file at ``path`` contains ``text``
CLI Example:
.. code-block:: bash
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
'''
path = os.path.expanduser(path)
if n... |
.. deprecated:: 0. 17. 0 Use: func: search instead. | def contains_regex(path, regex, lchar=''):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return True if the given regular expression matches on any line in the text
of a given file.
If the lchar argument (leading char) is specified, it
will strip `lchar` from the left side of e... |
.. deprecated:: 0. 17. 0 Use: func: search instead. | def contains_glob(path, glob_expr):
'''
.. deprecated:: 0.17.0
Use :func:`search` instead.
Return ``True`` if the given glob matches a string in the named file
CLI Example:
.. code-block:: bash
salt '*' file.contains_glob /etc/foobar '*cheese*'
'''
path = os.path.expanduse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.