code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def find_changelogs(session, name, candidates): repos = filter_repo_urls(candidates=candidates) # if we are lucky and there isn't a valid repo URL in our URL candidates, we need to go deeper # and check the URLs if they contain a link to a repo if not repos: logger.info("No repo found, tryi...
Tries to find changelogs on the given URL candidates :param session: requests Session instance :param name: str, project name :param candidates: list, URL candidates :return: tuple, (set(changelog URLs), set(repo URLs))
def find_git_repo(session, name, candidates): repos = filter_repo_urls(candidates=candidates) # if we are lucky and there isn't a valid repo URL in our URL candidates, we need to go deeper # and check the URLs if they contain a link to a repo if not repos: logger.info("No repo found, tryi...
Tries to find git repos on the given URL candidates :param session: requests Session instance :param name: str, project name :param candidates: list, URL candidates :return: tuple, (set(git URLs), set(repo URLs))
def get_urls(session, name, data, find_changelogs_fn, **kwargs): # if this package has valid meta data, build up a list of URL candidates we can possibly # search for changelogs on candidates = [ url for url in [data.get(attr) for attr in ( "project_uri", "homepage_uri", "wi...
Gets URLs to changelogs. :param session: requests Session instance :param name: str, package name :param data: dict, meta data :param find_changelogs_fn: function, find_changelogs :return: tuple, (set(changelog URLs), set(repo URLs))
def complete(text, state): for cmd in COMMANDS: if cmd.startswith(text): if not state: return cmd else: state -= 1
Auto complete scss constructions in interactive mode.
def readcfg(filepath, section): cfg = cp.ConfigParser() cfg.read(filepath) if not cfg.has_section(section): print('The section "{sec}" is not in the config file {file}.' .format(sec=section, file=filepath)) cfg = create_oedb_config_file(filepath...
Reads the configuration file. If section is not available, calls create_oedb_config_file to add the new section to an existing config.ini. Parameters ---------- filepath : str Absolute path of config file including the filename itself section : str Section in config file which c...
def get_connection_details(section): print('Please enter your connection details:') dialect = input('Enter input value for `dialect` (default: psycopg2): ') or 'psycopg2' username = input('Enter value for `username`: ') database = input('Enter value for `database`: ') host = input('Enter value ...
Asks the user for the database connection details and returns them as a ConfigParser-object. Parameters ---------- None Returns ------- cfg : configparser.ConfigParser Used for configuration file parser language.
def connection(filepath=None, section='oep'): # define default filepath if not provided if filepath is None: filepath = os.path.join(os.path.expanduser("~"), '.egoio', 'config.ini') # does the file exist? if not os.path.isfile(filepath): print('DB config file {file} not found. ' ...
Instantiate a database connection (for the use with SQLAlchemy). The keyword argument `filepath` specifies the location of the config file that contains database connection information. If not given, the default of `~/.egoio/config.ini` applies. Parameters ---------- filepath : str Abs...
def get_url_map(): map = {} path = os.path.join( os.path.dirname(os.path.realpath(__file__)), # current working dir ../ "custom", # ../custom/ "pypi", # ../custom/pypi/ "map.txt" # ../custom/pypi/map.txt ) with open(path) as f: for line in f.readlines(): ...
Loads custom/pypi/map.txt and builds a dict where map[package_name] = url :return: dict, urls
def get_urls(session, name, data, find_changelogs_fn, **kwargs): # check if there's a changelog in ../custom/pypi/map.txt map = get_url_map() if name.lower().replace("_", "-") in map: logger.info("Package {name}'s URL is in pypi/map.txt, returning".format(name=name)) return [map[name.lo...
Gets URLs to changelogs. :param session: requests Session instance :param name: str, package name :param data: dict, meta data :param find_changelogs_fn: function, find_changelogs :return: tuple, (set(changelog URLs), set(repo URLs))
def validate_args(self): from ..mixins import ModelMixin for arg in ("instance", "decider", "identifier", "fields", "default_language"): if getattr(self, arg) is None: raise AttributeError("%s must not be None" % arg) if not isinstance(self.instance, (Model...
Validates arguments.
def active_language(self): # Current instance language (if user uses activate_language() method) if self._language is not None: return self._language # Current site language (translation.get_language()) current = utils.get_language() if current in self.suppo...
Returns active language.
def translation_instances(self): return [ instance for k, v in six.iteritems(self.instance._linguist_translations) for instance in v.values() ]
Returns translation instances.
def get_cache( self, instance, translation=None, language=None, field_name=None, field_value=None, ): is_new = bool(instance.pk is None) try: cached_obj = instance._linguist_translations[field_name][language] if not ca...
Returns translation from cache.
def set_cache( self, instance=None, translation=None, language=None, field_name=None, field_value=None, ): if instance is not None and translation is not None: cached_obj = CachedTranslation.from_object(translation) instance._l...
Add a new translation into the cache.
def _filter_or_exclude(self, negate, *args, **kwargs): from .models import Translation new_args = self.get_cleaned_args(args) new_kwargs = self.get_cleaned_kwargs(kwargs) translation_args = self.get_translation_args(args) translation_kwargs = self.get_translation_kwarg...
Overrides default behavior to handle linguist fields.
def _get_concrete_fields_with_model(self): return [ (f, f.model if f.model != self.model else None) for f in self.model._meta.get_fields() if f.concrete and ( not f.is_relation or f.one_to_one or (f.many_to_one and f.related_model) ...
For compatibility with Django<=1.10. Replace old `_meta.get_concrete_fields_with_model`. https://docs.djangoproject.com/en/1.10/ref/models/meta/
def linguist_field_names(self): return list(self.model._linguist.fields) + list( utils.get_language_fields(self.model._linguist.fields) )
Returns linguist field names (example: "title" and "title_fr").
def has_linguist_kwargs(self, kwargs): for k in kwargs: if self.is_linguist_lookup(k): return True return False
Parses the given kwargs and returns True if they contain linguist lookups.
def has_linguist_args(self, args): linguist_args = [] for arg in args: condition = self._get_linguist_condition(arg) if condition: linguist_args.append(condition) return bool(linguist_args)
Parses the given args and returns True if they contain linguist lookups.
def get_translation_args(self, args): translation_args = [] for arg in args: condition = self._get_linguist_condition(arg, transform=True) if condition: translation_args.append(condition) return translation_args
Returns linguist args from model args.
def get_translation_kwargs(self, kwargs): lks = [] for k, v in six.iteritems(kwargs): if self.is_linguist_lookup(k): lks.append( utils.get_translation_lookup(self.model._linguist.identifier, k, v) ) translation_kwargs = {}...
Returns linguist lookup kwargs (related to Translation model).
def is_linguist_lookup(self, lookup): field = utils.get_field_name_from_lookup(lookup) # To keep default behavior with "FieldError: Cannot resolve keyword". if ( field not in self.concrete_field_names and field in self.linguist_field_names ): ...
Returns true if the given lookup is a valid linguist lookup.
def _get_linguist_condition(self, condition, reverse=False, transform=False): # We deal with a node if isinstance(condition, Q): children = [] for child in condition.children: parsed = self._get_linguist_condition( condition=child, rev...
Parses Q tree and returns linguist lookups or model lookups if reverse is True.
def get_cleaned_args(self, args): if not args: return args cleaned_args = [] for arg in args: condition = self._get_linguist_condition(arg, True) if condition: cleaned_args.append(condition) return cleaned_args
Returns positional arguments for related model query.
def get_cleaned_kwargs(self, kwargs): cleaned_kwargs = kwargs.copy() if kwargs is not None: for k in kwargs: if self.is_linguist_lookup(k): del cleaned_kwargs[k] return cleaned_kwargs
Returns concrete field lookups.
def with_translations(self, **kwargs): force = kwargs.pop("force", False) if self._prefetch_translations_done and force is False: return self self._prefetched_translations_cache = utils.get_grouped_translations( self, **kwargs ) self._prefetch_...
Prefetches translations. Takes three optional keyword arguments: * ``field_names``: ``field_name`` values for SELECT IN * ``languages``: ``language`` values for SELECT IN * ``chunks_length``: fetches IDs by chunk
def available_languages(self): from .models import Translation return ( Translation.objects.filter( identifier=self.linguist_identifier, object_id=self.pk ) .values_list("language", flat=True) .distinct() .order_by("la...
Returns available languages.
def get_translations(self, language=None): from .models import Translation if not self.pk: return Translation.objects.none() return Translation.objects.get_translations(obj=self, language=language)
Returns available (saved) translations for this instance.
def delete_translations(self, language=None): from .models import Translation return Translation.objects.delete_translations(obj=self, language=language)
Deletes related translations.
def override_language(self, language): previous_language = self._linguist.language self._linguist.language = language yield self._linguist.language = previous_language
Context manager to override the instance language.
def _save_table( self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None, ): updated = super(ModelMixin, self)._save_table( raw=raw, cls=cls, force_insert=force_inse...
Overwrites model's ``_save_table`` method to save translations after instance has been saved (required to retrieve the object ID for ``Translation`` model). Preferred over overriding the object's ``save`` method to ensure that `pre_save` and ``post_save`` signals happen respecti...
def validate_meta(meta): if not isinstance(meta, (dict,)): raise TypeError('Model Meta "linguist" must be a dict') required_keys = ("identifier", "fields") for key in required_keys: if key not in meta: raise KeyError('Model Meta "linguist" dict requires %s to be defined', ...
Validates Linguist Meta attribute.
def default_value_getter(field): def default_value_func_getter(self): localized_field = utils.build_localized_field_name( field, self._linguist.active_language ) value = getattr(self, localized_field) if value: return value default_field = utils...
When accessing to the name of the field itself, the value in the current language will be returned. Unless it's set, the value in the default language will be returned.
def default_value_setter(field): def default_value_func_setter(self, value): localized_field = utils.build_localized_field_name( field, self._linguist.active_language ) setattr(self, localized_field, value) return default_value_func_setter
When setting to the name of the field itself, the value in the current language will be set.
def field_factory(base_class): from .fields import TranslationField class TranslationFieldField(TranslationField, base_class): pass TranslationFieldField.__name__ = "Translation%s" % base_class.__name__ return TranslationFieldField
Takes a field base class and wrap it with ``TranslationField`` class.
def create_translation_field(translated_field, language): cls_name = translated_field.__class__.__name__ if not isinstance(translated_field, tuple(SUPPORTED_FIELDS.keys())): raise ImproperlyConfigured("%s is not supported by Linguist." % cls_name) translation_class = field_factory(translated_...
Takes the original field, a given language, a decider model and return a Field class for model.
def connect(self): ''' Connect to the drone. :raises RuntimeError: if the drone is connected or closed already. ''' if self.connected: raise RuntimeError( '{} is connected already'.format(self.__class__.__name__)) if self.closed: r...
Connect to the drone. :raises RuntimeError: if the drone is connected or closed already.
def close(self): ''' Exit all threads and disconnect the drone. This method has no effect if the drone is closed already or not connected yet. ''' if not self.connected: return if self.closed: return self.closed = True self...
Exit all threads and disconnect the drone. This method has no effect if the drone is closed already or not connected yet.
def _set_flags(self, **flags): ''' Set the flags of this argument. Example: ``int_param._set_flags(a=1, b=2, c=4, d=8)`` ''' self._flags = enum.IntEnum('_flags', flags) self.__dict__.update(self._flags.__members__) self._patch_flag_doc(f _set_flags(self, **flags)...
Set the flags of this argument. Example: ``int_param._set_flags(a=1, b=2, c=4, d=8)``
def delete_translations(sender, instance, **kwargs): if issubclass(sender, (ModelMixin,)): instance._linguist.decider.objects.filter( identifier=instance.linguist_identifier, object_id=instance.pk ).delete()
Deletes related instance's translations when instance is deleted.
def draw_tree(node, child_iter=lambda n: n.children, text_str=str): return LeftAligned(traverse=Traversal(get_text=text_str, get_children=child_iter), draw=LegacyStyle())(node)
Support asciitree 0.2 API. This function solely exist to not break old code (using asciitree 0.2). Its use is deprecated.
def render(self, node): lines = [] children = self.traverse.get_children(node) lines.append(self.draw.node_label(self.traverse.get_text(node))) for n, child in enumerate(children): child_tree = self.render(child) if n == len(children) - 1: ...
Renders a node. This function is used internally, as it returns a list of lines. Use :func:`~asciitree.LeftAligned.__call__` instead.
def get_language(): lang = _get_language() if not lang: return get_fallback_language() langs = [l[0] for l in settings.SUPPORTED_LANGUAGES] if lang not in langs and "-" in lang: lang = lang.split("-")[0] if lang in langs: return lang return settings.DEFAULT_LANGU...
Returns an active language code that is guaranteed to be in settings.SUPPORTED_LANGUAGES.
def activate_language(instances, language): language = ( language if language in get_supported_languages() else get_fallback_language() ) for instance in instances: instance.activate_language(language)
Activates the given language for the given instances.
def load_class(class_path, setting_name=None): if not isinstance(class_path, six.string_types): try: class_path, app_label = class_path except: if setting_name: raise exceptions.ImproperlyConfigured( CLASS_PATH_ERROR % (setting_name, s...
Loads a class given a class_path. The setting value may be a string or a tuple. The setting_name parameter is only there for pretty error output, and therefore is optional.
def get_model_string(model_name): setting_name = "LINGUIST_%s_MODEL" % model_name.upper().replace("_", "") class_path = getattr(settings, setting_name, None) if not class_path: return "linguist.%s" % model_name elif isinstance(class_path, basestring): parts = class_path.split(".") ...
Returns the model string notation Django uses for lazily loaded ForeignKeys (eg 'auth.User') to prevent circular imports. This is needed to allow our crazy custom model usage.
def get_translation_lookup(identifier, field, value): # Split by transformers parts = field.split("__") # Store transformers transformers = parts[1:] if len(parts) > 1 else None # defaults to "title" and default language field_name = parts[0] language = get_fallback_language() na...
Mapper that takes a language field, its value and returns the related lookup for Translation model.
def get_grouped_translations(instances, **kwargs): grouped_translations = collections.defaultdict(list) if not instances: return grouped_translations if not isinstance(instances, collections.Iterable): instances = [instances] if isinstance(instances, QuerySet): model = in...
Takes instances and returns grouped translations ready to be set in cache.
def every(secs): ''' Generator that yields for every *secs* seconds. Example: >>> for _ in every(0.1): ... print('Hello') You get ``Hello`` output every 0.1 seconds. ''' time_stated = time.monotonic() while True: time_yielded = time.monotonic() yield ti...
Generator that yields for every *secs* seconds. Example: >>> for _ in every(0.1): ... print('Hello') You get ``Hello`` output every 0.1 seconds.
def get_free_udp_port(): ''' Get a free UDP port. Note this is vlunerable to race conditions. ''' import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 0)) addr = sock.getsockname() sock.close() return addr[1f get_free_udp_port(): '''...
Get a free UDP port. Note this is vlunerable to race conditions.
def get_available_languages(self, obj): return obj.available_languages if obj is not None else self.model.objects.none()
Returns available languages for current object.
def languages_column(self, obj): languages = self.get_available_languages(obj) return '<span class="available-languages">{0}</span>'.format( " ".join(languages) )
Adds languages columns.
def prefetch_translations(instances, **kwargs): from .mixins import ModelMixin if not isinstance(instances, collections.Iterable): instances = [instances] populate_missing = kwargs.get("populate_missing", True) grouped_translations = utils.get_grouped_translations(instances, **kwargs) ...
Prefetches translations for the given instances. Can be useful for a list of instances.
def get_translations(self, obj, language=None): lookup = {"identifier": obj.linguist_identifier, "object_id": obj.pk} if language is not None: lookup["language"] = language return self.get_queryset().filter(**lookup)
Shorcut method to retrieve translations for a given object.
def save_translations(self, instances): if not isinstance(instances, (list, tuple)): instances = [instances] for instance in instances: translations = [] for obj in instance._linguist.translation_instances: if obj.field_name: ...
Saves cached translations (cached in model instances as dictionaries).
def _pack(self, seq='SEQUNSET'): ''' Packs the command into *bytes* :param seq: sequence number :rtype: bytes ''' return 'AT*{clsname}={seq}{argl_wc}\r'.format( clsname=type(self).__name__, seq=seq, argl_wc=b''.join(self._iter_packed_...
Packs the command into *bytes* :param seq: sequence number :rtype: bytes
def takeoff(self): ''' Sends the takeoff command. ''' self.send(at.REF(at.REF.input.start)f takeoff(self): ''' Sends the takeoff command. ''' self.send(at.REF(at.REF.input.start))
Sends the takeoff command.
def emergency(self): ''' Sends the emergency command. ''' self.send(at.REF(at.REF.input.select)f emergency(self): ''' Sends the emergency command. ''' self.send(at.REF(at.REF.input.select))
Sends the emergency command.
def _move(self, roll=0, pitch=0, gaz=0, yaw=0): ''' Same as sending :py:class:`~pyardrone.at.PCMD` command with progressive flag. ''' self.send(at.PCMD(at.PCMD.flag.progressive, roll, pitch, gaz, yaw)f _move(self, roll=0, pitch=0, gaz=0, yaw=0): ''' Same as sendin...
Same as sending :py:class:`~pyardrone.at.PCMD` command with progressive flag.
def encode(number, checksum=False, split=0): number = int(number) if number < 0: raise ValueError("number '%d' is not a positive integer" % number) split = int(split) if split < 0: raise ValueError("split '%d' is not a positive integer" % split) check_symbol = '' if checks...
Encode an integer into a symbol string. A ValueError is raised on invalid input. If checksum is set to True, a check symbol will be calculated and appended to the string. If split is specified, the string will be divided into clusters of that size separated by hyphens. The encoded string is ...
def decode(symbol_string, checksum=False, strict=False): symbol_string = normalize(symbol_string, strict=strict) if checksum: symbol_string, check_symbol = symbol_string[:-1], symbol_string[-1] number = 0 for symbol in symbol_string: number = number * base + decode_symbols[symbol] ...
Decode an encoded symbol string. If checksum is set to True, the string is assumed to have a trailing check symbol which will be validated. If the checksum validation fails, a ValueError is raised. If strict is set to True, a ValueError is raised if the normalization step requires changes to the s...
def normalize(symbol_string, strict=False): if isinstance(symbol_string, string_types): if not PY3: try: symbol_string = symbol_string.encode('ascii') except UnicodeEncodeError: raise ValueError("string should only contain ASCII characters") e...
Normalize an encoded symbol string. Normalization provides error correction and prepares the string for decoding. These transformations are applied: 1. Hyphens are removed 2. 'I', 'i', 'L' or 'l' are converted to '1' 3. 'O' or 'o' are converted to '0' 4. All characters are converte...
def _get_translation_field_names(): from .models import Translation fields = [f.name for f in Translation._meta.get_fields()] fields.remove("id") return fields
Returns Translation base model field names (excepted "id" field).
def send(self, command, *, log=True): ''' :param pyardrone.at.base.ATCommand command: command to send Sends the command to the drone, with an internal increasing sequence number. this method is thread-safe. ''' with self.sequence_number_mutex: self.se...
:param pyardrone.at.base.ATCommand command: command to send Sends the command to the drone, with an internal increasing sequence number. this method is thread-safe.
def setup_requires(): from pkg_resources import parse_version required = ['cython>=0.24.0'] numpy_requirement = 'numpy>=1.7.1' try: import numpy except Exception: required.append(numpy_requirement) else: if parse_version(numpy.__version__) < parse_version('1.7.1'): ...
Return required packages Plus any version tests and warnings
def _build_block_context(template, context): # Ensure there's a BlockContext before rendering. This allows blocks in # ExtendsNodes to be found by sub-templates (allowing {{ block.super }} and # overriding sub-blocks to work). if BLOCK_CONTEXT_KEY not in context.render_context: context.ren...
Populate the block context with BlockNodes from parent templates.
def _render_template_block_nodelist(nodelist, block_name, context): # Attempt to find the wanted block in the current template. for node in nodelist: # If the wanted block was found, return it. if isinstance(node, BlockNode): # No matter what, add this block to the rendering co...
Recursively iterate over a node to find the wanted block.
def render_block_to_string(template_name, block_name, context=None): # Like render_to_string, template_name can be a string or a list/tuple. if isinstance(template_name, (tuple, list)): t = loader.select_template(template_name) else: t = loader.get_template(template_name) # Create...
Loads the given template_name and renders the given block with the given dictionary as context. Returns a string. template_name The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find ...
def get_host_path(root, path, instance=None): r_val = resolve_value(path) if isinstance(r_val, dict): r_instance = instance or 'default' r_path = resolve_value(r_val.get(r_instance)) if not r_path: raise ValueError("No path defined for instance {0}.".format(r_instance)) ...
Generates the host path for a container volume. If the given path is a dictionary, uses the entry of the instance name. :param root: Root path to prepend, if ``path`` does not already describe an absolute path. :type root: unicode | str | AbstractLazyObject :param path: Path string or dictionary of per...
def from_client(cls, client): if hasattr(client, 'client_configuration'): return client.client_configuration kwargs = {'client': client} for attr in cls.init_kwargs: if hasattr(client, attr): kwargs[attr] = getattr(client, attr) if hasattr...
Constructs a configuration object from an existing client instance. If the client has already been created with a configuration object, returns that instance. :param client: Client object to derive the configuration from. :type client: docker.client.Client :return: ClientConfiguration
def get_init_kwargs(self): init_kwargs = {} for k in self.init_kwargs: if k in self.core_property_set: init_kwargs[k] = getattr(self, k) elif k in self: init_kwargs[k] = self[k] return init_kwargs
Generates keyword arguments for creating a new Docker client instance. :return: Keyword arguments as defined through this configuration. :rtype: dict
def get_client(self): client = self._client if not client: self._client = client = self.client_constructor(**self.get_init_kwargs()) client.client_configuration = self # Client might update the version number after construction. updated_version = ...
Retrieves or creates a client instance from this configuration object. If instantiated from this configuration, the resulting object is also cached in the property ``client`` and a reference to this configuration is stored on the client object. :return: Client object instance. :rtype: d...
def exec_commands(self, action, c_name, run_cmds, **kwargs): client = action.client exec_results = [] for run_cmd in run_cmds: cmd = run_cmd.cmd cmd_user = run_cmd.user log.debug("Creating exec command in container %s with user %s: %s.", c_name, cmd_u...
Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :param run_cmds: Commands to run. :type run_cmds: list[dockermap.map.input.ExecComman...
def exec_container_commands(self, action, c_name, **kwargs): config_cmds = action.config.exec_commands if not config_cmds: return None return self.exec_commands(action, c_name, run_cmds=config_cmds)
Runs all configured commands of a container configuration inside the container instance. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :return: List of exec command return values (e...
def prepare_path(path, replace_space, replace_sep, expandvars, expanduser): r_path = path if expandvars: r_path = os.path.expandvars(r_path) if expanduser: r_path = os.path.expanduser(r_path) if replace_sep and os.sep != posixpath.sep: r_path = r_path.replace(os.path.sep, po...
Performs `os.path` replacement operations on a path string. :param path: Path string :type path: unicode | str :param replace_space: Mask spaces with backslash. :param replace_sep: Replace potentially different path separators with POSIX path notation (use :const:`posixpath.sep`). :type replace_sep...
def format_command(cmd, shell=False): def _split_cmd(): line = None for part in cmd.split(' '): line = part if line is None else '{0} {1}'.format(line, part) if part[-1] != '\\': yield line line = None if line is not None: ...
Converts a command line to the notation as used in a Dockerfile ``CMD`` and ``ENTRYPOINT`` command. In shell notation, this returns a simple string, whereas by default it returns a JSON-list format with the command and arguments. :param cmd: Command line as a string or tuple. :type cmd: unicode | str |...
def format_expose(expose): if isinstance(expose, six.string_types): return expose, elif isinstance(expose, collections.Iterable): return map(six.text_type, expose) return six.text_type(expose),
Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple. :param: Port numbers, can be as integer, string, or a list/tuple of those. :type expose: int | unicode | str | list | tuple :return: A tuple, to be separated by spaces before inserting in a Dockerfile...
def prefix(self, prefix='#', *args): self.write(prefix) if args: self.write(' ') self.writeline(' '.join(map(six.text_type, args)))
Prefix one or multiple arguments with a Dockerfile command. The default is ``#``, for comments. Multiple args will be separated by a space. :param prefix: Dockerfile command to use, e.g. ``ENV`` or ``RUN``. :type prefix: unicode | str :param args: Arguments to be prefixed.
def prefix_all(self, prefix='#', *lines): for line in lines: if isinstance(line, (tuple, list)): self.prefix(prefix, *line) elif line: self.prefix(prefix, line) else: self.blank()
Same as :func:`~prefix`, for multiple lines. :param prefix: Dockerfile command to use, e.g. ``ENV`` or ``RUN``. :type prefix: unicode | str :param lines: Lines with arguments to be prefixed. :type lines: collections.Iterable[unicode | str]
def add_archive(self, src_file, remove_final=False): with tarfile.open(src_file, 'r') as tf: member_names = [member.name for member in tf.getmembers() if posixpath.sep not in member.name] self.prefix_all('ADD', *zip(member_name...
Adds the contents of another tarfile to the build. It will be repackaged during context generation, and added to the root level of the file system. Therefore, it is not required that tar (or compression utilities) is present in the base image. :param src_file: Tar archive to add. :type ...
def add_volume(self, path): self.check_not_finalized() if self.volumes is None: self.volumes = [path] else: self.volumes.append(path)
Add a shared volume (i.e. with the ``VOLUME`` command). Not actually written until finalized. :param path: Path to the shared volume.
def write(self, input_str): self.check_not_finalized() if isinstance(input_str, six.binary_type): self.fileobj.write(input_str) else: self.fileobj.write(input_str.encode('utf-8'))
Adds content to the Dockerfile. :param input_str: Content. :type input_str: unicode | str
def finalize(self): if self._finalized: return if self._remove_files: for filename in self._remove_files: self.prefix('RUN', 'rm -Rf', filename) self.blank() if self._volumes is not None: self.prefix('VOLUME', json.dumps(se...
Finalizes the Dockerfile. Before the buffer is practically marked as read-only, the following Dockerfile commands are written: * ``RUN rm -R`` on each files marked for automatic removal; * ``VOLUME`` for shared volumes; * ``USER`` as the default user for following commands; * ``...
def merge_dependency(self, item, resolve_parent, parents): dep = [] for parent_key in parents: if item == parent_key: raise CircularDependency(item, True) if parent_key.config_type == ItemType.CONTAINER: parent_dep = resolve_parent(parent_...
Merge dependencies of current configuration with further dependencies; in this instance, it means that in case of container configuration first parent dependencies are checked, and then immediate dependencies of the current configuration should be added to the list, but without duplicating any entries. ...
def expand_node(loader, node, expand_method): if isinstance(node, yaml.nodes.ScalarNode): val = loader.construct_scalar(node) return expand_method(val) elif isinstance(node, yaml.nodes.MappingNode): val = loader.construct_mapping(node) for d_key, d_val in six.iteritems(val):...
Expands paths on a YAML document node. If it is a sequence node (list) items on the first level are expanded. For a mapping node (dict), values are expanded. :param loader: YAML loader. :type loader: yaml.loader.SafeLoader :param node: Document node. :type node: ScalarNode, MappingNode, or Sequence...
def load_map(stream, name=None, check_integrity=True, check_duplicates=True): map_dict = yaml.safe_load(stream) if isinstance(map_dict, dict): map_name = name or map_dict.pop('name', None) if not map_name: raise ValueError("No map name provided, and none found in YAML stream.") ...
Loads a ContainerMap configuration from a YAML document stream. :param stream: YAML stream. :type stream: file :param name: Name of the ContainerMap. If not provided, will be attempted to read from a ``name`` attribute on the document root level. :type name: unicode | str :param check_integri...
def load_clients(stream, configuration_class=ClientConfiguration): client_dict = yaml.safe_load(stream) if isinstance(client_dict, dict): return {client_name: configuration_class(**client_config) for client_name, client_config in six.iteritems(client_dict)} raise ValueError("Val...
Loads client configurations from a YAML document stream. :param stream: YAML stream. :type stream: file :param configuration_class: Class of the configuration object to create. :type configuration_class: class :return: A dictionary of client configuration objects. :rtype: dict[unicode | str, do...
def load_map_file(filename, name=None, check_integrity=True): if name == '': base_name = os.path.basename(filename) map_name, __, __ = os.path.basename(base_name).rpartition(os.path.extsep) else: map_name = name with open(filename, 'r') as f: return load_map(f, name=map_...
Loads a ContainerMap configuration from a YAML file. :param filename: YAML file name. :type filename: unicode | str :param name: Name of the ContainerMap. If ``None`` will attempt to find a ``name`` element on the root level of the document; an empty string names the map according to the file, withou...
def load_clients_file(filename, configuration_class=ClientConfiguration): with open(filename, 'r') as f: return load_clients(f, configuration_class=configuration_class)
Loads client configurations from a YAML file. :param filename: YAML file name. :type filename: unicode | str :param configuration_class: Class of the configuration object to create. :type configuration_class: class :return: A dictionary of client configuration objects. :rtype: dict[unicode | st...
def get_policy(self): if not self._policy: self._policy = self.policy_class(self._maps, self._clients) return self._policy
Returns an instance of :attr:`~policy_class`. :return: An instance of the current policy class. :rtype: dockermap.map.policy.base.BasePolicy
def get_state_generator(self, action_name, policy, kwargs): state_generator_cls = self.generators[action_name][0] state_generator = state_generator_cls(policy, kwargs) return state_generator
Returns the state generator to be used for the given action. :param action_name: Action identifier name. :type action_name: unicode | str :param policy: An instance of the current policy class. :type policy: dockermap.map.policy.base.BasePolicy :param kwargs: Keyword arguments. ...
def get_action_generator(self, action_name, policy, kwargs): action_generator_cls = self.generators[action_name][1] action_generator = action_generator_cls(policy, kwargs) return action_generator
Returns the action generator to be used for the given action. :param action_name: Action identifier name. :type action_name: unicode | str :param policy: An instance of the current policy class. :type policy: dockermap.map.policy.base.BasePolicy :param kwargs: Keyword arguments....
def get_states(self, action_name, config_name, instances=None, map_name=None, **kwargs): policy = self.get_policy() _set_forced_update_ids(kwargs, policy.container_maps, map_name or self._default_map, instances) state_generator = self.get_state_generator(action_name, policy, kwargs) ...
Returns a generator of states in relation to the indicated action. :param action_name: Action name. :type action_name: unicode | str :param config_name: Name(s) of container configuration(s) or MapConfigId tuple(s). :type config_name: unicode | str | collections.Iterable[unicode | str] ...
def get_actions(self, action_name, config_name, instances=None, map_name=None, **kwargs): policy = self.get_policy() action_generator = self.get_action_generator(action_name, policy, kwargs) for state in self.get_states(action_name, config_name, instances=instances, map_name=map_name, *...
Returns the entire set of actions performed for the indicated action name. :param action_name: Action name. :type action_name: unicode | str :param config_name: Name(s) of container configuration(s) or MapConfigId tuple(s). :type config_name: unicode | str | collections.Iterable[unicode...
def run_actions(self, action_name, config_name, instances=None, map_name=None, **kwargs): policy = self.get_policy() results = [] runner = self.get_runner(policy, kwargs) for action_list in self.get_actions(action_name, config_name, instances, map_name, **kwargs): tr...
Runs the entire set of actions performed for the indicated action name. On any client failure this raises a :class:`~dockermap.map.exceptions.ActionRunnerException`, where partial results can be reviewed in the property ``results``, or :class:`~dockermap.exceptions.MiscInvocationError` if no particular ...
def create(self, container, instances=None, map_name=None, **kwargs): return self.run_actions('create', container, instances=instances, map_name=map_name, **kwargs)
Creates container instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance name to create. If not specified, will create all instances as specified in the configuration (or just one default instance). :...
def start(self, container, instances=None, map_name=None, **kwargs): return self.run_actions('start', container, instances=instances, map_name=map_name, **kwargs)
Starts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to start. If not specified, will start all instances as specified in the configuration (or just one default instance). :param map_na...
def restart(self, container, instances=None, map_name=None, **kwargs): return self.run_actions('restart', container, instances=instances, map_name=map_name, **kwargs)
Restarts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will restart all instances as specified in the configuration (or just one default instance). :type inst...
def stop(self, container, instances=None, map_name=None, **kwargs): return self.run_actions('stop', container, instances=instances, map_name=map_name, **kwargs)
Stops instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will stop all instances as specified in the configuration (or just one default instance). :type instances:...
def remove(self, container, instances=None, map_name=None, **kwargs): return self.run_actions('remove', container, instances=instances, map_name=map_name, **kwargs)
Remove instances from a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to remove. If not specified, will remove all instances as specified in the configuration (or just one default instance). :type inst...