INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Ensure the data pipeline exists with matching definition.
def present(name, pipeline_objects=None, pipeline_objects_from_pillars='boto_datapipeline_pipeline_objects', parameter_objects=None, parameter_objects_from_pillars='boto_datapipeline_parameter_objects', parameter_values=None, parameter_values_from_pillars='bot...
Return true if the pipeline exists and the definition matches.
def _pipeline_present_with_definition(name, expected_pipeline_objects, expected_parameter_objects, expected_parameter_values, region, key, keyid, profile): ''' Return true if the pipeline exists and...
Return standardized pipeline objects to be used for comparing
def _cleaned(_pipeline_objects): """Return standardized pipeline objects to be used for comparing Remove year, month, and day components of the startDateTime so that data pipelines with the same time of day but different days are considered equal. """ pipeline_objects = copy.deepcopy(_pipeline_...
Return v1 == v2. Compares list dict recursively.
def _recursive_compare(v1, v2): ''' Return v1 == v2. Compares list, dict, recursively. ''' if isinstance(v1, list): if v2 is None: v2 = [] if len(v1) != len(v2): return False v1.sort(key=_id_or_key) v2.sort(key=_id_or_key) for x, y in zip(v...
Return the value at key id or key.
def _id_or_key(list_item): ''' Return the value at key 'id' or 'key'. ''' if isinstance(list_item, dict): if 'id' in list_item: return list_item['id'] if 'key' in list_item: return list_item['key'] return list_item
Return string diff of pipeline definitions.
def _diff(old_pipeline_definition, new_pipeline_definition): ''' Return string diff of pipeline definitions. ''' old_pipeline_definition.pop('ResponseMetadata', None) new_pipeline_definition.pop('ResponseMetadata', None) diff = salt.utils.data.decode(difflib.unified_diff( salt.utils.jso...
Return standardized format for lists/ dictionaries.
def _standardize(structure): ''' Return standardized format for lists/dictionaries. Lists of dictionaries are sorted by the value of the dictionary at its primary key ('id' or 'key'). OrderedDict's are converted to basic dictionaries. ''' def mutating_helper(structure): if isinstanc...
Return a list of pipeline objects that compose the pipeline
def _pipeline_objects(pipeline_objects_from_pillars, pipeline_object_overrides): ''' Return a list of pipeline objects that compose the pipeline pipeline_objects_from_pillars The pillar key to use for lookup pipeline_object_overrides Pipeline objects to use. Will override objects read ...
Return a list of parameter objects that configure the pipeline
def _parameter_objects(parameter_objects_from_pillars, parameter_object_overrides): ''' Return a list of parameter objects that configure the pipeline parameter_objects_from_pillars The pillar key to use for lookup parameter_object_overrides Parameter objects to use. Will override obje...
Return a dictionary of parameter values that configure the pipeline
def _parameter_values(parameter_values_from_pillars, parameter_value_overrides): ''' Return a dictionary of parameter values that configure the pipeline parameter_values_from_pillars The pillar key to use for lookup parameter_value_overrides Parameter values to use. Will override value...
Convert a dictionary to a list of dictionaries where each element has a key value pair { id: key }. This makes it easy to override pillar values while still satisfying the boto api.
def _dict_to_list_ids(objects): ''' Convert a dictionary to a list of dictionaries, where each element has a key value pair {'id': key}. This makes it easy to override pillar values while still satisfying the boto api. ''' list_with_ids = [] for key, value in six.iteritems(objects): ...
Transforms dictionary into pipeline object properties.
def _properties_from_dict(d, key_name='key'): ''' Transforms dictionary into pipeline object properties. The output format conforms to boto's specification. Example input: { 'a': '1', 'b': { 'ref': '2' }, } Example output: ...
Ensure a pipeline with the service_name does not exist
def absent(name, region=None, key=None, keyid=None, profile=None): ''' Ensure a pipeline with the service_name does not exist name Name of the service to ensure a data pipeline does not exist for. region Region to connect to. key Secret key to be used. keyid A...
Deserialize any string or stream like object into a Python data structure.
def deserialize(stream_or_string, **options): ''' Deserialize any string or stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower json/simplejson module. ''' try: if not isinstance(stream_or_str...
Serialize Python data to JSON.
def serialize(obj, **options): ''' Serialize Python data to JSON. :param obj: the data structure to serialize :param options: options given to lower json/simplejson module. ''' try: if 'fp' in options: return salt.utils.json.dump(obj, _json_module=_json, **options) ...
Ensure that the named database is present with the specified properties
def present(name, character_set=None, collate=None, **connection_args): ''' Ensure that the named database is present with the specified properties name The name of the database to manage ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Da...
Ensure that the named database is absent
def absent(name, **connection_args): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if db exists and remove it if __salt__['mysql.db_...
Return the net. find runner options.
def _get_net_runner_opts(): ''' Return the net.find runner options. ''' runner_opts = __opts__.get('runners', {}).get('net.find', {}) return { 'target': runner_opts.get('target', _DEFAULT_TARGET), 'expr_form': runner_opts.get('expr_form', _DEFAULT_EXPR_FORM), 'ignore_interfac...
Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code.
def _get_mine(fun): ''' Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code. ''' if fun in _CACHE and _CACHE[fun]: return _CACHE[fun] net_runner_opts = _get_net_runner_opts() _CACHE[fun] = __salt__['mine.get'](net_runner_opts....
Display or return the rows.
def _display_runner(rows, labels, title, display=_DEFAULT_DISPLAY): ''' Display or return the rows. ''' if display: net_runner_opts = _get_net_runner_opts() if net_runner_opts.get('outputter') == 'table': ret = salt.output.out_format({'rows': rows, 'labels': labels}, ...
Helper to search the interfaces IPs using the MAC address.
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.i...
Helper to get the interfaces hardware address using the IP Address.
def _find_interfaces_mac(ip): # pylint: disable=invalid-name ''' Helper to get the interfaces hardware address using the IP Address. ''' all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') for device, device_ipaddrs in six.iteritems(all_ipaddrs): if not ...
Search for interfaces details in the following mine functions:
def interfaces(device=None, interface=None, title=None, pattern=None, ipnet=None, best=True, display=_DEFAULT_DISPLAY): ''' Search for interfaces details in the following mine functions: - net.interfaces - net.ipa...
Search for entries in the ARP tables using the following mine functions:
def findarp(device=None, interface=None, mac=None, ip=None, display=_DEFAULT_DISPLAY): # pylint: disable=invalid-name ''' Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return i...
Search in the MAC Address tables using the following mine functions:
def findmac(device=None, mac=None, interface=None, vlan=None, display=_DEFAULT_DISPLAY): ''' Search in the MAC Address tables, using the following mine functions: - net.mac Optional arguments: device Return interface data from a certain device only. interface Return data sele...
Search in the LLDP neighbors using the following mine functions:
def lldp(device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY): ''' Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a ce...
Search in all possible entities ( Interfaces MAC tables ARP tables LLDP neighbors ) using the following mine functions:
def find(addr, best=True, display=_DEFAULT_DISPLAY): ''' Search in all possible entities (Interfaces, MAC tables, ARP tables, LLDP neighbors), using the following mine functions: - net.mac - net.arp - net.lldp - net.ipaddrs - net.interfaces This function has the advantage that it k...
Execute multiple search tasks. This function is based on the find function. Depending on the search items some information might overlap.
def multi_find(*patterns, **kwargs): ''' Execute multiple search tasks. This function is based on the `find` function. Depending on the search items, some information might overlap. Optional arguments: best: ``True`` Return only the best match with the interfaces IP networks wh...
Recursive generator providing the infrastructure for augtools print behavior.
def _recurmatch(path, aug): ''' Recursive generator providing the infrastructure for augtools print behavior. This function is based on test_augeas.py from Harald Hoyer <harald@redhat.com> in the python-augeas repository ''' if path: clean_path = path.rstrip('/*') yield...
Return a copy of the string after the specified prefix was removed from the beginning of the string
def _lstrip_word(word, prefix): ''' Return a copy of the string after the specified prefix was removed from the beginning of the string ''' if six.text_type(word).startswith(prefix): return six.text_type(word)[len(prefix):] return word
Checks the validity of the load_path returns a sanitized version with invalid paths removed.
def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ''' if load_path is None or not isinstance(load_path, six.string_types): return None _paths = [] for _path in load_path.split(':'): if os.path...
Execute Augeas commands
def execute(context=None, lens=None, commands=(), load_path=None): ''' Execute Augeas commands .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' augeas.execute /files/etc/redis/redis.conf \\ commands='["set bind 0.0.0.0", "set maxmemory 1G"]' context ...
Get a value for a specific augeas path
def get(path, value='', load_path=None): ''' Get a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.get /files/etc/hosts/1/ ipaddr path The path to get the value of value The optional value to get .. versionadded:: 2016.3.0 ...
Set a value for a specific augeas path
def setvalue(*args): ''' Set a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost This will set the first entry in /etc/hosts to localhost CLI Example: .. code-block:: bash salt '*' augeas....
Get matches for path expression
def match(path, value='', load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.match /files/etc/services/service-name ssh path The path to match value The value to match on .. versionadded:: 2016.3.0 load_pa...
Get matches for path expression
def remove(path, load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-s...
List the direct children of a node
def ls(path, load_path=None): # pylint: disable=C0103 ''' List the direct children of a node CLI Example: .. code-block:: bash salt '*' augeas.ls /files/etc/passwd path The path to list .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories ...
Returns recursively the complete tree of a node
def tree(path, load_path=None): ''' Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directori...
Return a list of all installed kernels.
def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' pkg_re = re.compile(r'^{0}-[\d.-]+-{1}$'.format( _package_prefix(), _kernel_type())) pkgs = __salt__['pkg.list_pkgs'](versions_as_list=...
Upgrade the kernel and optionally reboot the system.
def upgrade(reboot=False, at_time=None): ''' Upgrade the kernel and optionally reboot the system. reboot : False Request a reboot if a new kernel is available. at_time : immediate Schedule the reboot at some point in the future. This argument is ignored if ``reboot=False``. See...
Remove a specific version of the kernel.
def remove(release): ''' Remove a specific version of the kernel. release The release number of an installed kernel. This must be the entire release number as returned by :py:func:`~salt.modules.kernelpkg_linux_apt.list_installed`, not the package name. CLI Example: .. cod...
Remove all unused kernel packages from the system.
def cleanup(keep_latest=True): ''' Remove all unused kernel packages from the system. keep_latest : True In the event that the active kernel is not the latest one installed, setting this to True will retain the latest kernel package, in addition to the active one. If False, all kernel ...
Compare function for package version sorting
def _cmp_version(item1, item2): ''' Compare function for package version sorting ''' vers1 = _LooseVersion(item1) vers2 = _LooseVersion(item2) if vers1 < vers2: return -1 if vers1 > vers2: return 1 return 0
Ensure that the key exists in redis with the value specified
def string(name, value, expire=None, expireat=None, **connection_args): ''' Ensure that the key exists in redis with the value specified name Redis key to manage value Data to persist in key expire Sets time to live for key in seconds expireat Sets expiration ...
Ensure key absent from redis
def absent(name, keys=None, **connection_args): ''' Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used ''' ret = {'name': name, 'changes': {}, 'result': True, ...
Set this redis instance as a slave.
def slaveof(name, sentinel_host=None, sentinel_port=None, sentinel_password=None, **connection_args): ''' Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port ...
This module can also be run directly for testing Args: detail|list: Provide detail or version list. system|system + user: System installed and System and User installs.
def __main(): '''This module can also be run directly for testing Args: detail|list : Provide ``detail`` or version ``list``. system|system+user: System installed and System and User installs. ''' if len(sys.argv) < 3: sys.stderr.write('usage: {0} <detail|list> <syste...
Squished GUID ( SQUID ) to GUID.
def __squid_to_guid(self, squid): ''' Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided. ...
Test for 1 as a number or a string and return True if it is.
def __one_equals_true(value): ''' Test for ``1`` as a number or a string and return ``True`` if it is. Args: value: string or number or None. Returns: bool: ``True`` if 1 otherwise ``False``. ''' if isinstance(value, six.integer_types) and value ...
Calls RegQueryValueEx
def __reg_query_value(handle, value_name): ''' Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str)...
Return the install time or provide an estimate of install time.
def install_time(self): ''' Return the install time, or provide an estimate of install time. Installers or even self upgrading software must/should update the date held within InstallDate field when they change versions. Some installers do not set ``InstallDate`` at all so we us...
For the uninstall section of the registry return the name value.
def get_install_value(self, value_name, wanted_type=None): ''' For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match ...
For the product section of the registry return the name value.
def get_product_value(self, value_name, wanted_type=None): ''' For the product section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match ...
For installers which follow the Microsoft Installer standard returns the Upgrade code.
def upgrade_code(self): ''' For installers which follow the Microsoft Installer standard, returns the ``Upgrade code``. Returns: value (str): ``Upgrade code`` GUID for installed software. ''' if not self.__squid: # Must have a valid squid for an u...
For installers which follow the Microsoft Installer standard returns a list of patches applied.
def list_patches(self): ''' For installers which follow the Microsoft Installer standard, returns a list of patches applied. Returns: value (list): Long name of the patch. ''' if not self.__squid: # Must have a valid squid for an upgrade code to e...
Return version number which is stored in binary format.
def version_binary(self): ''' Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ''' # Under MSI 'Version' is a 'REG_DWORD' which then sets other registry # values like Displ...
Returns information on a package.
def pkg_version_list(self, pkg_id): ''' Returns information on a package. Args: pkg_id (str): Package Id of the software/component. Returns: list: List of version numbers installed. ''' pkg_data = self.__reg_software.get(pkg_id, None) if ...
Provided with a valid Windows Security Identifier ( SID ) and returns a Username
def __sid_to_username(sid): ''' Provided with a valid Windows Security Identifier (SID) and returns a Username Args: sid (str): Security Identifier (SID). Returns: str: Username in the format of username@realm or username@computer. ''' if sid is ...
Determine the Package ID of a software/ component using the software/ component publisher name whether its a software or a component and if its 32bit or 64bit archiecture.
def __software_to_pkg_id(self, publisher, name, is_component, is_32bit): ''' Determine the Package ID of a software/component using the software/component ``publisher``, ``name``, whether its a software or a component, and if its 32bit or 64bit archiecture. Args: pub...
This returns the version and where the version string came from based on instructions under version_capture if version_capture is missing it defaults to value of display - version.
def __version_capture_slp(self, pkg_id, version_binary, version_display, display_name): ''' This returns the version and where the version string came from, based on instructions under ``version_capture``, if ``version_capture`` is missing, it defaults to value of display-version. ...
Update data with the next software found
def __collect_software_info(self, sid, key_software, use_32bit): ''' Update data with the next software found ''' reg_soft_info = RegSoftwareInfo(key_software, sid, use_32bit) # Check if the registry entry is a valid. # a) Cannot manage software without at least a displ...
This searches the uninstall keys in the registry to find a match in the sub keys it will return a dict with the display name as the key and the version as the value.. sectionauthor:: Damon Atkins <https:// github. com/ damon - atkins >.. versionadded:: Carbon
def __get_software_details(self, user_pkgs): ''' This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value .. sectionauthor:: Damon Atkins <https://github.com/damon-atkins>...
Force params to be strings unless they should remain a different type
def enforce_types(key, val): ''' Force params to be strings unless they should remain a different type ''' non_string_params = { 'ssl_verify': bool, 'insecure_auth': bool, 'disable_saltenv_mapping': bool, 'env_whitelist': 'stringlist', 'env_blacklist': 'stringlist...
Return the names of remote refs ( stripped of the remote name ) and tags which are map to the branches and tags.
def _get_envs_from_ref_paths(self, refs): ''' Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags. ''' def _check_ref(env_set, rname): ''' Add the appropriate saltenv(s) to the set ''' ...
Programmatically determine config value based on the desired saltenv
def add_conf_overlay(cls, name): ''' Programmatically determine config value based on the desired saltenv ''' def _getconf(self, tgt_env='base'): strip_sep = lambda x: x.rstrip(os.sep) \ if name in ('root', 'mountpoint') \ else x if...
Check if the relative root path exists in the checked - out copy of the remote. Return the full path to that relative root if it does exist otherwise return None.
def check_root(self): ''' Check if the relative root path exists in the checked-out copy of the remote. Return the full path to that relative root if it does exist, otherwise return None. ''' # No need to pass an environment to self.root() here since per-saltenv #...
Remove stale refs so that they are no longer seen as fileserver envs
def clean_stale_refs(self): ''' Remove stale refs so that they are no longer seen as fileserver envs ''' cleaned = [] cmd_str = 'git remote prune origin' # Attempt to force all output to plain ascii english, which is what some parsing code # may expect. #...
Clear update. lk
def clear_lock(self, lock_type='update'): ''' Clear update.lk ''' lock_file = self._get_lock_file(lock_type=lock_type) def _add_error(errlist, exc): msg = ('Unable to remove update lock for {0} ({1}): {2} ' .format(self.url, lock_file, exc)) ...
For the config options which need to be maintained in the git config ensure that the git config file is configured as desired.
def enforce_git_config(self): ''' For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired. ''' git_config = os.path.join(self.gitdir, 'config') conf = salt.utils.configparser.GitConfigParser() ...
Fetch the repo. If the local copy was updated return True. If the local copy was already up - to - date return False.
def fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. This function requires that a _fetch() function be implemented in a sub-class. ''' try: with self.gen_lock(lock_ty...
Place a lock file if ( and only if ) it does not already exist.
def _lock(self, lock_type='update', failhard=False): ''' Place a lock file if (and only if) it does not already exist. ''' try: fh_ = os.open(self._get_lock_file(lock_type), os.O_CREAT | os.O_EXCL | os.O_WRONLY) with os.fdopen(fh_, 'wb'):...
Place an lock file and report on the success/ failure. This is an interface to be used by the fileserver runner so it is hard - coded to perform an update lock. We aren t using the gen_lock () contextmanager here because the lock is meant to stay and not be automatically removed.
def lock(self): ''' Place an lock file and report on the success/failure. This is an interface to be used by the fileserver runner, so it is hard-coded to perform an update lock. We aren't using the gen_lock() contextmanager here because the lock is meant to stay and not be ...
Set and automatically clear a lock
def gen_lock(self, lock_type='update', timeout=0, poll_interval=0.5): ''' Set and automatically clear a lock ''' if not isinstance(lock_type, six.string_types): raise GitLockError( errno.EINVAL, 'Invalid lock_type \'{0}\''.format(lock_type) ...
Check if an environment is exposed by comparing it against a whitelist and blacklist.
def env_is_exposed(self, tgt_env): ''' Check if an environment is exposed by comparing it against a whitelist and blacklist. ''' return salt.utils.stringutils.check_whitelist_blacklist( tgt_env, whitelist=self.saltenv_whitelist, blacklist=self....
Resolve dynamically - set branch
def get_checkout_target(self): ''' Resolve dynamically-set branch ''' if self.role == 'git_pillar' and self.branch == '__env__': try: return self.all_saltenvs except AttributeError: # all_saltenvs not configured for this remote ...
Return a tree object for the specified environment
def get_tree(self, tgt_env): ''' Return a tree object for the specified environment ''' if not self.env_is_exposed(tgt_env): return None tgt_ref = self.ref(tgt_env) if tgt_ref is None: return None for ref_type in self.ref_types: ...
Examine self. id and assign self. url ( and self. branch for git_pillar )
def get_url(self): ''' Examine self.id and assign self.url (and self.branch, for git_pillar) ''' if self.role in ('git_pillar', 'winrepo'): # With winrepo and git_pillar, the remote is specified in the # format '<branch> <url>', so that we can get a unique identif...
Return the expected result of an os. walk on the linkdir based on the mountpoint value.
def linkdir_walk(self): ''' Return the expected result of an os.walk on the linkdir, based on the mountpoint value. ''' try: # Use cached linkdir_walk if we've already run this return self._linkdir_walk except AttributeError: self._link...
Checkout the configured branch/ tag. We catch an Exception class here instead of a specific exception class because the exceptions raised by GitPython when running these functions vary in different versions of GitPython.
def checkout(self): ''' Checkout the configured branch/tag. We catch an "Exception" class here instead of a specific exception class because the exceptions raised by GitPython when running these functions vary in different versions of GitPython. ''' tgt_ref = self...
Initialize/ attach to a remote using GitPython. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function.
def init_remote(self): ''' Initialize/attach to a remote using GitPython. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function. ''' new = False if not os.listdir(self.cachedir): # Repo cac...
Get list of directories for the target environment using GitPython
def dir_list(self, tgt_env): ''' Get list of directories for the target environment using GitPython ''' ret = set() tree = self.get_tree(tgt_env) if not tree: return ret if self.root(tgt_env): try: tree = tree / self.root(tg...
Check the refs and return a list of the ones which can be used as salt environments.
def envs(self): ''' Check the refs and return a list of the ones which can be used as salt environments. ''' ref_paths = [x.path for x in self.repo.refs] return self._get_envs_from_ref_paths(ref_paths)
Fetch the repo. If the local copy was updated return True. If the local copy was already up - to - date return False.
def _fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. ''' origin = self.repo.remotes[0] try: fetch_results = origin.fetch() except AssertionError: fetch_res...
Get file list for the target environment using GitPython
def file_list(self, tgt_env): ''' Get file list for the target environment using GitPython ''' files = set() symlinks = {} tree = self.get_tree(tgt_env) if not tree: # Not found, return empty objects return files, symlinks if self.r...
Find the specified file in the specified environment
def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: # Branch/tag/SHA not found in repo return None, None, None blob = None depth = 0 while True:...
Return a git. Tree object matching a head ref fetched into refs/ remotes/ origin/
def get_tree_from_branch(self, ref): ''' Return a git.Tree object matching a head ref fetched into refs/remotes/origin/ ''' try: return git.RemoteReference( self.repo, 'refs/remotes/origin/{0}'.format(ref)).commit.tree except Va...
Return a git. Tree object matching a tag ref fetched into refs/ tags/
def get_tree_from_tag(self, ref): ''' Return a git.Tree object matching a tag ref fetched into refs/tags/ ''' try: return git.TagReference( self.repo, 'refs/tags/{0}'.format(ref)).commit.tree except ValueError: return None
Return a git. Tree object matching a SHA
def get_tree_from_sha(self, ref): ''' Return a git.Tree object matching a SHA ''' try: return self.repo.rev_parse(ref).tree except (gitdb.exc.ODBError, AttributeError): return None
Using the blob object write the file to the destination path
def write_file(self, blob, dest): ''' Using the blob object, write the file to the destination path ''' with salt.utils.files.fopen(dest, 'wb+') as fp_: blob.stream_data(fp_)
Checkout the configured branch/ tag
def checkout(self): ''' Checkout the configured branch/tag ''' tgt_ref = self.get_checkout_target() local_ref = 'refs/heads/' + tgt_ref remote_ref = 'refs/remotes/origin/' + tgt_ref tag_ref = 'refs/tags/' + tgt_ref try: local_head = self.repo....
Clean stale local refs so they don t appear as fileserver environments
def clean_stale_refs(self, local_refs=None): # pylint: disable=arguments-differ ''' Clean stale local refs so they don't appear as fileserver environments ''' try: if pygit2.GIT_FETCH_PRUNE: # Don't need to clean anything, pygit2 can do it by itself ...
Initialize/ attach to a remote using pygit2. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function.
def init_remote(self): ''' Initialize/attach to a remote using pygit2. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function. ''' # https://github.com/libgit2/pygit2/issues/339 # https://github.com/lib...
Get a list of directories for the target environment using pygit2
def dir_list(self, tgt_env): ''' Get a list of directories for the target environment using pygit2 ''' def _traverse(tree, blobs, prefix): ''' Traverse through a pygit2 Tree object recursively, accumulating all the empty directories within it in the "b...
Fetch the repo. If the local copy was updated return True. If the local copy was already up - to - date return False.
def _fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. ''' origin = self.repo.remotes[0] refs_pre = self.repo.listall_references() fetch_kwargs = {} # pygit2 radically chang...
Get file list for the target environment using pygit2
def file_list(self, tgt_env): ''' Get file list for the target environment using pygit2 ''' def _traverse(tree, blobs, prefix): ''' Traverse through a pygit2 Tree object recursively, accumulating all the file paths and symlink info in the "blobs" dict ...
Find the specified file in the specified environment
def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: # Branch/tag/SHA not found in repo return None, None, None blob = None mode = None depth = 0...
Return a pygit2. Tree object matching a head ref fetched into refs/ remotes/ origin/
def get_tree_from_branch(self, ref): ''' Return a pygit2.Tree object matching a head ref fetched into refs/remotes/origin/ ''' try: return self.peel(self.repo.lookup_reference( 'refs/remotes/origin/{0}'.format(ref))).tree except KeyError: ...
Return a pygit2. Tree object matching a SHA
def get_tree_from_sha(self, ref): ''' Return a pygit2.Tree object matching a SHA ''' try: return self.repo.revparse_single(ref).tree except (KeyError, TypeError, ValueError, AttributeError): return None
Assign attributes for pygit2 callbacks
def setup_callbacks(self): ''' Assign attributes for pygit2 callbacks ''' if PYGIT2_VERSION >= _LooseVersion('0.23.2'): self.remotecallbacks = pygit2.RemoteCallbacks( credentials=self.credentials) if not self.ssl_verify: # Override ...
Check the username and password/ keypair info for validity. If valid set a credentials attribute consisting of the appropriate Pygit2 credentials object. Return False if a required auth param is not present. Return True if the required auth parameters are present ( or auth is not configured ) otherwise failhard if ther...
def verify_auth(self): ''' Check the username and password/keypair info for validity. If valid, set a 'credentials' attribute consisting of the appropriate Pygit2 credentials object. Return False if a required auth param is not present. Return True if the required auth parameters...