Clear update.lk

    ``remote`` can either be a dictionary containing repo configuration
    information, or a pattern. If the latter, then remotes for which the URL
    matches the pattern will be locked.
499780
def clear_lock(remote=None):
    '''
    
    '''
    def _do_clear_lock(repo):
        def _add_error(errlist, repo, exc):
            msg = ('Unable to remove update lock for {0} ({1}): {2} '
                   .format(repo['url'], repo['lockfile'], exc))
            log.debug(msg)
            errlist.append(msg)
        success = []
        failed = []
        if os.path.exists(repo['lockfile']):
            try:
                os.remove(repo['lockfile'])
            except OSError as exc:
                if exc.errno == errno.EISDIR:
                    # Somehow this path is a directory. Should never happen
                    # unless some wiseguy manually creates a directory at this
                    # path, but just in case, handle it.
                    try:
                        shutil.rmtree(repo['lockfile'])
                    except OSError as exc:
                        _add_error(failed, repo, exc)
                else:
                    _add_error(failed, repo, exc)
            else:
                msg = 'Removed lock for {0}'.format(repo['url'])
                log.debug(msg)
                success.append(msg)
        return success, failed

    if isinstance(remote, dict):
        return _do_clear_lock(remote)

    cleared = []
    errors = []
    for repo in init():
        if remote:
            try:
                if remote not in repo['url']:
                    continue
            except TypeError:
                # remote was non-string, try again
                if six.text_type(remote) not in repo['url']:
                    continue
        success, failed = _do_clear_lock(repo)
        cleared.extend(success)
        errors.extend(failed)
    return cleared, errors
761825
def _set_remote(self, name, url):
        
        remotes = self._get_remotes()
        exising_url = remotes.get(name)
        if exising_url == url:
            logger.info('Remote already exists %s <%s>', name, url)
            return
        if not exising_url:
            logger.info('Adding remote %s <%s>', name, url)
            self.log_call(['git', 'remote', 'add', name, url], cwd=self.cwd)
        else:
            logger.info('Remote remote %s <%s> -> <%s>',
                        name, exising_url, url)
            self.log_call(['git', 'remote', 'rm', name], cwd=self.cwd)
            self.log_call(['git', 'remote', 'add', name, url], cwd=self.cwd)
714906
def repo_pull(repo_dir, repo_url, fetch=False):
    """"""
    # Make sure the repository is reset to the master branch.
    repo = Repo(repo_dir)
    repo.git.clean("-df")
    repo.git.reset("--hard")
    repo.git.checkout("master")
    repo.head.reset(index=True, working_tree=True)

    # Compile the refspec appropriately to ensure
    # that if the repo is from github it includes
    # all the refs needed, including PR's.
    refspec_list = [
        "+refs/heads/*:refs/remotes/origin/*",
        "+refs/heads/*:refs/heads/*",
        "+refs/tags/*:refs/tags/*"
    ]
    if "github.com" in repo_url:
        refspec_list.extend([
            "+refs/pull/*:refs/remotes/origin/pr/*",
            "+refs/heads/*:refs/remotes/origin/*"])

    # Only get the latest updates if requested.
    if fetch:
        repo.git.fetch(["-u", "-v", "-f",
                        repo_url,
                        refspec_list])
    return repo
630490
def determine_remotely
      # Remove password field from URI, as libvirt doesn't support it directly. We can use it for passphrase if needed.
      lv_uri = URI::Generic.build(:scheme => @connection_uri.scheme, :userinfo => @connection_uri.user,
                                  :host => @connection_uri.host, :path => @connection_uri.path,
                                  :query => @connection_uri.query)

      # The authentication only pertains to libvirtd itself and _not_ the transport (e.g. SSH).
      conn = Libvirt::open_auth(lv_uri.to_s, [Libvirt::CRED_AUTHNAME, Libvirt::CRED_PASSPHRASE]) do |cred|
        case cred["type"]
          when Libvirt::CRED_AUTHNAME
            @connection_uri.user
          when Libvirt::CRED_PASSPHRASE
            @connection_uri.password
        end
      end

      if dom = get_existing_domain(conn, @appliance_name)
        unless @overwrite
          @log.fatal("A domain already exists with the name #{@appliance_name}. Set overwrite:true to automatically destroy and undefine it.")
          raise RuntimeError, "Domain '#{@appliance_name}' already exists"  #Make better specific exception
        end
        @log.info("Undefining existing domain #{@appliance_name}")
        undefine_domain(dom)
      end

      guest = @libvirt_capabilities.determine_capabilities(conn, @previous_plugin_info)

      raise "Remote libvirt machine offered no viable guests!" if guest.nil?

      xml = generate_xml(guest)
      @log.info("Defining domain #{@appliance_name}")
      conn.define_domain_xml(xml)
      xml
    ensure
      if conn
        conn.close unless conn.closed?
      end
    end
907333
def is_remote_added(remote):
    '''
    
    '''
    out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remotes')

    lines = out.splitlines()
    for item in lines:
        i = re.split(r'\t+', item.rstrip('\t'))
        if i[0] == remote:
            return True
    return False
527972
def git_fetch(repo_dir, remote=None, refspec=None, verbose=False, tags=True):
    
    command = ['git', 'fetch']
    if not remote:
        command.append('--all')
    else:
        remote = pipes.quote(remote)
    command.extend(['--update-head-ok'])
    if tags:
        command.append('--tags')
    if verbose:
        command.append('--verbose')
    if remote:
        command.append(remote)
    if refspec:
        command.append(refspec)
    return execute_git_command(command, repo_dir=repo_dir)
1030243
function RemoteLS (opts) {
  var _this = this

  _.extend(this, {
    logger: console,
    development: true, // include dev dependencies.
    optional: true, // include optional dependencies.
    peer: false, // include peer dependencies.
    verbose: false,
    registry: require('registry-url')(), // URL of registry to ls.
    queue: async.queue(function (task, done) {
      _this._loadPackageJson(task, done)
    }, 8),
    tree: {},
    flat: {}
  }, require('./config')(), opts)

  this.queue.pause()
}
404606
function initRemote () {
      remoteName = "remote-" + crypto.createHash('md5').update(options.remote).digest('hex').substring(0, 6);

      if (shelljs.exec('git remote', {silent: true}).output.indexOf(remoteName) === -1) {
        log.subhead('Creating remote.');
        execWrap('git remote add ' + remoteName + ' ' + options.remote);
      }
    }
1142200
function checkRemote (remotes, remote) {
  if (remotes === "ALL") {
    return true;
  }

  if (!_.isArray(remotes)) {
    remotes = _.invoke(remotes.split(","), "trim");
  }

  return _.any(remotes, _.partial(minimatch, remote));
}
1021186
def enforce_git_config(self):
        '''
        
        '''
        git_config = os.path.join(self.gitdir, 'config')
        conf = salt.utils.configparser.GitConfigParser()
        if not conf.read(git_config):
            log.error('Failed to read from git config file %s', git_config)
        else:
            # We are currently enforcing the following git config items:
            # 1. Fetch URL
            # 2. refspecs used in fetch
            # 3. http.sslVerify
            conf_changed = False
            remote_section = 'remote "origin"'

            # 1. URL
            try:
                url = conf.get(remote_section, 'url')
            except salt.utils.configparser.NoSectionError:
                # First time we've init'ed this repo, we need to add the
                # section for the remote to the git config
                conf.add_section(remote_section)
                conf_changed = True
                url = None
            log.debug(
                'Current fetch URL for %s remote \'%s\': %s (desired: %s)',
                self.role, self.id, url, self.url
            )
            if url != self.url:
                conf.set(remote_section, 'url', self.url)
                log.debug(
                    'Fetch URL for %s remote \'%s\' set to %s',
                    self.role, self.id, self.url
                )
                conf_changed = True

            # 2. refspecs
            try:
                refspecs = sorted(
                    conf.get(remote_section, 'fetch', as_list=True))
            except salt.utils.configparser.NoOptionError:
                # No 'fetch' option present in the remote section. Should never
                # happen, but if it does for some reason, don't let it cause a
                # traceback.
                refspecs = []
            desired_refspecs = sorted(self.refspecs)
            log.debug(
                'Current refspecs for %s remote \'%s\': %s (desired: %s)',
                self.role, self.id, refspecs, desired_refspecs
            )
            if refspecs != desired_refspecs:
                conf.set_multivar(remote_section, 'fetch', self.refspecs)
                log.debug(
                    'Refspecs for %s remote \'%s\' set to %s',
                    self.role, self.id, desired_refspecs
                )
                conf_changed = True

            # 3. http.sslVerify
            try:
                ssl_verify = conf.get('http', 'sslVerify')
            except salt.utils.configparser.NoSectionError:
                conf.add_section('http')
                ssl_verify = None
            except salt.utils.configparser.NoOptionError:
                ssl_verify = None
            desired_ssl_verify = six.text_type(self.ssl_verify).lower()
            log.debug(
                'Current http.sslVerify for %s remote \'%s\': %s (desired: %s)',
                self.role, self.id, ssl_verify, desired_ssl_verify
            )
            if ssl_verify != desired_ssl_verify:
                conf.set('http', 'sslVerify', desired_ssl_verify)
                log.debug(
                    'http.sslVerify for %s remote \'%s\' set to %s',
                    self.role, self.id, desired_ssl_verify
                )
                conf_changed = True

            # Write changes, if necessary
            if conf_changed:
                with salt.utils.files.fopen(git_config, 'w') as fp_:
                    conf.write(fp_)
                    log.debug(
                        'Config updates for %s remote \'%s\' written to %s',
                        self.role, self.id, git_config
                    )
259102
def remote_for_request(request)
      repo_owner = request.head.repo.owner.login
      remote_url = server.remote_url_for(repo_owner)
      remotes = remotes_for_url(remote_url)
      if remotes.empty?
        remote = "review_#{repo_owner}"
        git_call("remote add #{remote} #{remote_url}", debug_mode, true)
      else
        remote = remotes.first
      end
      remote
    end
376187
def init_remotes(self, remotes, per_remote_overrides=(),
                     per_remote_only=PER_REMOTE_ONLY,
                     global_only=GLOBAL_ONLY):
        '''
        
        '''
        # The global versions of the auth params (gitfs_user,
        # gitfs_password, etc.) default to empty strings. If any of them
        # are defined and the provider is not one that supports auth, then
        # error out and do not proceed.
        override_params = copy.deepcopy(per_remote_overrides)
        global_auth_params = [
            '{0}_{1}'.format(self.role, x) for x in AUTH_PARAMS
            if self.opts['{0}_{1}'.format(self.role, x)]
        ]
        if self.provider in AUTH_PROVIDERS:
            override_params += AUTH_PARAMS
        elif global_auth_params:
            msg = (
                '{0} authentication was configured, but the \'{1}\' '
                '{0}_provider does not support authentication. The '
                'providers for which authentication is supported in {0} '
                'are: {2}.'.format(
                    self.role, self.provider, ', '.join(AUTH_PROVIDERS)
                )
            )
            if self.role == 'gitfs':
                msg += (
                    ' See the GitFS Walkthrough in the Salt documentation '
                    'for further information.'
                )
            log.critical(msg)
            failhard(self.role)

        per_remote_defaults = {}
        global_values = set(override_params)
        global_values.update(set(global_only))
        for param in global_values:
            key = '{0}_{1}'.format(self.role, param)
            if key not in self.opts:
                log.critical(
                    'Key \'%s\' not present in global configuration. This is '
                    'a bug, please report it.', key
                )
                failhard(self.role)
            per_remote_defaults[param] = enforce_types(key, self.opts[key])

        self.remotes = []
        for remote in remotes:
            repo_obj = self.git_providers[self.provider](
                self.opts,
                remote,
                per_remote_defaults,
                per_remote_only,
                override_params,
                self.cache_root,
                self.role
            )
            if hasattr(repo_obj, 'repo'):
                # Sanity check and assign the credential parameter
                repo_obj.verify_auth()
                repo_obj.setup_callbacks()
                if self.opts['__role'] == 'minion' and repo_obj.new:
                    # Perform initial fetch on masterless minion
                    repo_obj.fetch()

                # Reverse map to be used when running envs() to detect the
                # available envs.
                repo_obj.saltenv_revmap = {}

                for saltenv, saltenv_conf in six.iteritems(repo_obj.saltenv):
                    if 'ref' in saltenv_conf:
                        ref = saltenv_conf['ref']
                        repo_obj.saltenv_revmap.setdefault(
                            ref, []).append(saltenv)

                        if saltenv == 'base':
                            # Remove redundant 'ref' config for base saltenv
                            repo_obj.saltenv[saltenv].pop('ref')
                            if ref != repo_obj.base:
                                log.warning(
                                    'The \'base\' environment has been '
                                    'defined in the \'saltenv\' param for %s '
                                    'remote %s and will override the '
                                    'branch/tag specified by %s_base (or a '
                                    'per-remote \'base\' parameter).',
                                    self.role, repo_obj.id, self.role
                                )
                                # Rewrite 'base' config param
                                repo_obj.base = ref

                # Build list of all envs defined by ref mappings in the
                # per-remote 'saltenv' param. We won't add any matching envs
                # from the global saltenv map to the revmap.
                all_envs = []
                for env_names in six.itervalues(repo_obj.saltenv_revmap):
                    all_envs.extend(env_names)

                # Add the global saltenv map to the reverse map, skipping envs
                # explicitly mapped in the per-remote 'saltenv' param.
                for key, conf in six.iteritems(repo_obj.global_saltenv):
                    if key not in all_envs and 'ref' in conf:
                        repo_obj.saltenv_revmap.setdefault(
                            conf['ref'], []).append(key)

                self.remotes.append(repo_obj)

        # Don't allow collisions in cachedir naming
        cachedir_map = {}
        for repo in self.remotes:
            cachedir_map.setdefault(repo.cachedir, []).append(repo.id)

        collisions = [x for x in cachedir_map if len(cachedir_map[x]) > 1]
        if collisions:
            for dirname in collisions:
                log.critical(
                    'The following %s remotes have conflicting cachedirs: '
                    '%s. Resolve this using a per-remote parameter called '
                    '\'name\'.', self.role, ', '.join(cachedir_map[dirname])
                )
                failhard(self.role)

        if any(x.new for x in self.remotes):
            self.write_remote_map()
1355369
def do_remote(self):
        
        if self.verify_ssl:
            args = {"verify": self.verify_ssl}
        else:
            args = {}

        try:
            logging.debug('KeyBundle fetch keys from: {}'.format(self.source))
            r = self.httpc('GET', self.source, **args)
        except Exception as err:
            logger.error(err)
            raise UpdateFailed(
                REMOTE_FAILED.format(self.source, str(err)))

        if r.status_code == 200:  # New content
            self.time_out = time.time() + self.cache_time

            self.imp_jwks = self._parse_remote_response(r)
            if not isinstance(self.imp_jwks,
                              dict) or "keys" not in self.imp_jwks:
                raise UpdateFailed(MALFORMED.format(self.source))

            logger.debug("Loaded JWKS: %s from %s" % (r.text, self.source))
            try:
                self.do_keys(self.imp_jwks["keys"])
            except KeyError:
                logger.error("No 'keys' keyword in JWKS")
                raise UpdateFailed(MALFORMED.format(self.source))

        else:
            raise UpdateFailed(
                REMOTE_FAILED.format(self.source, r.status_code))
        self.last_updated = time.time()
        return True
1359514
def _check_remote_option(self, option):
        """"""
        if not self.telnet_opt_dict.has_key(option):
            self.telnet_opt_dict[option] = TelnetOption()
        return self.telnet_opt_dict[option].remote_option
778292
def remote_set(self, url, name='origin'):
        

        url = self.chomp_protocol(url)

        if self.remote_get(name):
            self.run(['remote', 'rm', 'name'])

        self.run(['remote', 'add', name, url])
        return self.remote_get(remote=name)
280342
def do_update
      # note that a recent fetch was performed by remote_differs? and even if
      # remotes have changed again in the brief interim it would invalidate
      # the decisions already made if we refetched now.
      git_repo = git_repo_for(@repo_dir)
      @logger.operation(:cleanup, "ensure no untracked files in #{@repo_dir}") do
        git_repo.hard_reset_to(nil)
        do_clean_all(git_repo)
      end
      do_checkout_revision(git_repo)
      do_clean_all(git_repo)  # clean again once we are on requested revision
      internal_update_tag(git_repo)
      true
    end
1048154
def _get_remote(self, cached=True):
        '''
        
        '''

        return self.m(
            'getting current remote',
            cmdd=dict(
                cmd='git remote show %s' % ('-n' if cached else ''),
                cwd=self.local
            ),
            verbose=False
        )