Return a list of hglib objects for the various hgfs remotes

def init():
    '''
    Return a list of hglib objects for the various hgfs remotes
    '''
    bp_ = os.path.join(__opts__['cachedir'], 'hgfs')
    new_remote = False
    repos = []

    per_remote_defaults = {}
    for param in PER_REMOTE_OVERRIDES:
        per_remote_defaults[param] = \
            six.text_type(__opts__['hgfs_{0}'.format(param)])

    for remote in __opts__['hgfs_remotes']:
        repo_conf = copy.deepcopy(per_remote_defaults)
        if isinstance(remote, dict):
            repo_url = next(iter(remote))
            per_remote_conf = dict(
                [(key, six.text_type(val)) for key, val in
                 six.iteritems(salt.utils.data.repack_dictlist(remote[repo_url]))]
            )
            if not per_remote_conf:
                log.error(
                    'Invalid per-remote configuration for hgfs remote %s. If '
                    'no per-remote parameters are being specified, there may '
                    'be a trailing colon after the URL, which should be '
                    'removed. Check the master configuration file.', repo_url
                )
                _failhard()

            branch_method = \
                per_remote_conf.get('branch_method',
                                    per_remote_defaults['branch_method'])
            if branch_method not in VALID_BRANCH_METHODS:
                log.error(
                    'Invalid branch_method \'%s\' for remote %s. Valid '
                    'branch methods are: %s. This remote will be ignored.',
                    branch_method, repo_url, ', '.join(VALID_BRANCH_METHODS)
                )
                _failhard()

            per_remote_errors = False
            for param in (x for x in per_remote_conf
                          if x not in PER_REMOTE_OVERRIDES):
                log.error(
                    'Invalid configuration parameter \'%s\' for remote %s. '
                    'Valid parameters are: %s. See the documentation for '
                    'further information.',
                    param, repo_url, ', '.join(PER_REMOTE_OVERRIDES)
                )
                per_remote_errors = True
            if per_remote_errors:
                _failhard()

            repo_conf.update(per_remote_conf)
        else:
            repo_url = remote

        if not isinstance(repo_url, six.string_types):
            log.error(
                'Invalid hgfs remote %s. Remotes must be strings, you may '
                'need to enclose the URL in quotes', repo_url
            )
            _failhard()

        try:
            repo_conf['mountpoint'] = salt.utils.url.strip_proto(
                repo_conf['mountpoint']
            )
        except TypeError:
            # mountpoint not specified
            pass

        hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
        repo_hash = hash_type(repo_url).hexdigest()
        rp_ = os.path.join(bp_, repo_hash)
        if not os.path.isdir(rp_):
            os.makedirs(rp_)

        if not os.listdir(rp_):
            # Only init if the directory is empty.
            hglib.init(rp_)
            new_remote = True
        try:
            repo = hglib.open(rp_)
        except hglib.error.ServerError:
            log.error(
                'Cache path %s (corresponding remote: %s) exists but is not '
                'a valid mercurial repository. You will need to manually '
                'delete this directory on the master to continue to use this '
                'hgfs remote.', rp_, repo_url
            )
            _failhard()
        except Exception as exc:
            log.error(
                'Exception \'%s\' encountered while initializing hgfs '
                'remote %s', exc, repo_url
            )
            _failhard()

        try:
            refs = repo.config(names='paths')
        except hglib.error.CommandError:
            refs = None

        # Do NOT put this if statement inside the except block above. Earlier
        # versions of hglib did not raise an exception, so we need to do it
        # this way to support both older and newer hglib.
        if not refs:
            # Write an hgrc defining the remote URL
            hgconfpath = os.path.join(rp_, '.hg', 'hgrc')
            with salt.utils.files.fopen(hgconfpath, 'w+') as hgconfig:
                hgconfig.write('[paths]\n')
                hgconfig.write(
                    salt.utils.stringutils.to_str(
                        'default = {0}\n'.format(repo_url)
                    )
                )

        repo_conf.update({
            'repo': repo,
            'url': repo_url,
            'hash': repo_hash,
            'cachedir': rp_,
            'lockfile': os.path.join(__opts__['cachedir'],
                                     'hgfs',
                                     '{0}.update.lk'.format(repo_hash))
        })
        repos.append(repo_conf)
        repo.close()

    if new_remote:
        remote_map = os.path.join(__opts__['cachedir'], 'hgfs/remote_map.txt')
        try:
            with salt.utils.files.fopen(remote_map, 'w+') as fp_:
                timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
                fp_.write('# hgfs_remote map as of {0}\n'.format(timestamp))
                for repo in repos:
                    fp_.write(
                        salt.utils.stringutils.to_str(
                            '{0} = {1}\n'.format(repo['hash'], repo['url'])
                        )
                    )
        except OSError:
            pass
        else:
            log.info('Wrote new hgfs_remote map to %s', remote_map)

    return repos