Esempio n. 1
0
def git_credentials(scheme, hostname, username, password, config=None, dry_run=False):
    if config is None:
        config = os.path.expanduser("~/.git-credentials")
    lines = []
    dirpath(os.path.dirname(config), dry_run=dry_run)
    if os.path.isfile(config):
        with codecs.open(config, "r", encoding="utf-8") as fd:
            lines = fd.readlines()
    new_lines = []
    found, write = False, True
    for line in lines:
        f_line = line.strip()
        if f_line.startswith("#"):
            new_lines.append(line)
        parsed_url = urlparse.urlparse(f_line)
        if parsed_url.scheme == scheme.lower() and parsed_url.hostname == hostname.lower():
            new_lines.append("%s://%s:%s@%s\n" % (scheme, username, password, hostname))
            found = True
            if parsed_url.username == username and parsed_url.password == password:
                write = False
        else:
            new_lines.append(line)
    if new_lines and new_lines[-1][-1:] != "\n":
        new_lines.append("\n")
    if not found:
        new_lines.append("%s://%s:%s@%s\n" % (scheme, username, password, hostname))
    if write:
        valid("File %(filename)s written.", filename=config)
        if not dry_run:
            with codecs.open(config, "w", encoding="utf-8") as fd:
                for line in new_lines:
                    fd.write(line)
Esempio n. 2
0
def _write_template(dst_filepath, template_package, template_dir, template_name, template_values, dry_run):
    template = Environment(loader=PackageLoader(template_package, template_dir)).get_template(template_name)
    content = template.render(**template_values)
    dirpath(os.path.dirname(dst_filepath), dry_run=dry_run)
    valid("File %(filename)s written.", filename=dst_filepath)
    if not dry_run:
        with codecs.open(dst_filepath, "w", encoding="utf-8") as fd:
            fd.write(content)
Esempio n. 3
0
def __write_bazsh_config(
    name, value, dry_run, bash_config, zsh_config, searched_pattern, pattern_to_add, check_previous_value=True
):
    if value is None:
        value = None
    if zsh_config is None:
        zsh_config = os.path.expanduser("~/.zshrc.sh")
    if bash_config is None:
        bash_config = os.path.expanduser("~/.bashrc")
    actual_value = None
    for config in (bash_config, zsh_config):
        if config is False:
            continue
        lines = []
        dirpath(os.path.dirname(config), dry_run=dry_run)
        if os.path.isfile(config):
            with codecs.open(config, "r", encoding="utf-8") as fd:
                lines = fd.readlines()
        new_lines = []
        found, write = False, True
        for line in lines:
            matcher = searched_pattern.match(line.strip())
            if not matcher:
                new_lines.append(line)
                continue
            actual_name = matcher.group(1)
            if value is not None:
                actual_value = matcher.group(2)
            elif value is None:
                pass
            if name != actual_name:
                new_lines.append(line)
                continue
            found = True
            if not check_previous_value or value.strip() == actual_value.strip():
                write = False
                new_lines.append(line)
                continue
            new_lines.append(pattern_to_add % {"name": name, "value": value})
        if not found:
            if new_lines and new_lines[-1][-1:] != "\n":
                new_lines.append("\n")
            new_lines.append(pattern_to_add % {"name": name, "value": value})
        if write:
            valid("File %(filename)s written.", filename=config)
            if not dry_run:
                with codecs.open(config, "w", encoding="utf-8") as fd:
                    for line in new_lines:
                        fd.write(line)
Esempio n. 4
0
def ssh_host(
    host,
    config=None,
    hostname=None,
    gssapidelegatecredentials=None,
    gssapiauthentication=None,
    proxycommand=None,
    user=None,
    gssapikeyexchange=None,
    dry_run=False,
):
    """ Garantit que les paramètres demandés sont dans le fichier de config .SSH. S'il le faut, réécrit le fichier en ajoutant les bonnes infos

    :param host: host à paramétrer
    :param config: emplacement du fichier de configuration SSH (sinon, il prend $HOME/.ssh/config)
    :param hostname:
    :param gssapidelegatecredentials: 'yes'
    :param gssapiauthentication: 'yes'
    :param proxycommand:
    :param user: '******'
    :param gssapikeyexchange: 'yes'
    :param dry_run: vrai : on n'écrit pas le fichier
    :type dry_run: bool
    :return:
    """
    if config is None:
        config = os.path.expanduser("~/.ssh/config")
    dirpath(os.path.dirname(config), dry_run=dry_run)
    required = {}
    to_write = []
    required_file = cStringIO()
    required_file.write("Host %s\n" % host)
    for (k, v) in (
        ("Hostname", hostname),
        ("GSSAPIAuthentication", gssapiauthentication),
        ("GSSAPIDelegateCredentials", gssapidelegatecredentials),
        ("ProxyCommand", proxycommand),
        ("User", user),
        ("GSSAPIKeyExchange", gssapikeyexchange),
    ):
        if v is not None:
            required[k] = v
            to_write.append((k, v))
            required_file.write("%s %s\n" % (k, v))
    required_file.seek(0)
    required_config = SSHConfig()
    # noinspection PyTypeChecker
    required_config.parse(required_file)
    required = required_config.lookup(host)

    if os.path.isfile(config):
        with codecs.open(config, "r", encoding="utf-8") as fd:
            ssh_config = SSHConfig()
            ssh_config.parse(fd)
        actual = ssh_config.lookup(host)
        for k in list(required.keys()):
            value = required[k]
            if actual.get(k) == value:
                del required[k]
    if not required:  # toutes les infos sont présentes
        return False
    new_lines = []
    if os.path.isfile(config):
        with codecs.open(config, "r", encoding="utf-8") as fd:
            lines = list(fd.readlines())
            remove = False
            for line in lines:
                f_line = line.strip().lower()
                if line and line[-1] != "\n":
                    line += "\n"
                if not f_line:
                    if not remove:
                        new_lines.append(line)
                    remove = False
                elif f_line.startswith("host "):
                    actual_hosts = f_line[5:].split()
                    new_hosts = list(filter(lambda x: x != host.lower(), actual_hosts))
                    if not new_hosts:
                        remove = True
                    elif new_hosts != actual_hosts:
                        new_lines.append("Host %s\n" % " ".join(new_hosts))
                    else:
                        new_lines.append(line)
                elif not remove:
                    new_lines.append(line)
    if new_lines and new_lines[-1].strip():
        new_lines.append("\n")
    new_lines.append("Host %s\n" % host)
    for k, v in to_write:
        new_lines.append("%s %s\n" % (k, v))
    new_lines.append("\n")
    valid("File %(filename)s written.", filename=config)
    if not dry_run:
        with codecs.open(config, "w", encoding="utf-8") as fd:
            for line in new_lines:
                fd.write(line)
    return True
Esempio n. 5
0
def python_mirror(
    extra_index=None,
    index=None,
    cert=None,
    allow_all_external=True,
    config_pip=None,
    config_easyinstall=None,
    config_buildout=None,
    dry_run=False,
):
    """
    :param extra_index: URL se finissant généralement par /simple, permettant de chercher des liens vers des paquets
    :param index: URL de base du miroir Pypi (exemple : https://pypi.python.org), on en déduira automatiquement {index}/simple et {index}/pypi
    :param cert: emplacement d'un fichier de certificat
    :param config_pip: emplacement de ~/.pip/pip.conf
    :param config_easyinstall: emplacement ~/.pydistutils.cfg
    :param dry_run:
    :return:
    """
    if config_easyinstall is None:
        config_easyinstall = os.path.expanduser("~/.pydistutils.cfg")
    if config_pip is None:
        config_pip = os.path.expanduser("~/.pip/pip.conf")
    if config_buildout is None:
        config_buildout = os.path.expanduser("~/.buildout/default.cfg")
    dirpath(os.path.dirname(config_pip), dry_run=dry_run)
    dirpath(os.path.dirname(config_easyinstall), dry_run=dry_run)
    dirpath(os.path.dirname(config_buildout), dry_run=dry_run)
    # on commence par pip.conf
    parser = configparser.ConfigParser()

    parser.read([config_pip])
    if not parser.has_section("global"):
        parser.add_section("global")
    write = False
    simple_index = None
    if index is not None:
        if index.endswith("/"):
            index = index[:-1]
        pypi_index = index + "/pypi"
        simple_index = index + "/simple"
        write = write or not parser.has_option("global", "index") or parser.get("global", "index") != pypi_index
        parser.set("global", "index", pypi_index)
        write = (
            write or not parser.has_option("global", "index-url") or parser.get("global", "index-url") != simple_index
        )
        parser.set("global", "index-url", simple_index)
    if cert is not None:
        write = write or not parser.has_option("global", "cert") or parser.get("global", "cert") != cert
        parser.set("global", "cert", cert)
    if allow_all_external is not None:
        write = (
            write
            or not parser.has_option("global", "allow-all-external")
            or parser.getboolean("global", "allow-all-external") != allow_all_external
        )
        parser.set("global", "allow-all-external", allow_all_external)
    if extra_index is not None:
        current_extra_indexes = []
        if parser.has_option("global", "extra-index-url"):
            current_extra_indexes = parser.get("global", "extra-index-url").splitlines()
        if extra_index not in current_extra_indexes:
            write = True
            current_extra_indexes.append(extra_index)
            parser.set("global", "extra-index-url", "\n".join(current_extra_indexes))
    if write:
        valid("File %(filename)s written.", filename=config_pip)
        if not dry_run:
            with open(config_pip, "w") as fd:
                parser.write(fd)
    # ensuite, on fait easyinstall
    parser = configparser.ConfigParser()
    parser.read([config_easyinstall])
    if not parser.has_section("easy_install"):
        parser.add_section("easy_install")
    if index is not None:
        write = (
            write
            or not parser.has_option("easy_install", "index_url")
            or parser.get("easy_install", "index_url") != simple_index
        )
        parser.set("easy_install", "index_url", simple_index)
    if extra_index is not None:
        current_extra_indexes = []
        if parser.has_option("easy_install", "find_links"):
            current_extra_indexes = parser.get("easy_install", "find_links").splitlines()
        if extra_index not in current_extra_indexes:
            write = True
            current_extra_indexes.append(extra_index)
            parser.set("easy_install", "find_links", "\n".join(current_extra_indexes))
    if write:
        valid("File %(filename)s written.", filename=config_easyinstall)
        if not dry_run:
            with open(config_easyinstall, "w") as fd:
                parser.write(fd)
    # ensuite, on fait buildout
    parser = configparser.ConfigParser()
    parser.read([config_buildout])
    if not parser.has_section("buildout"):
        parser.add_section("buildout")
    if index is not None:
        write = write or not parser.has_option("buildout", "index") or parser.get("buildout", "index") != simple_index
        parser.set("buildout", "index", simple_index)
    if write:
        valid("File %(filename)s written.", filename=config_buildout)
        if not dry_run:
            with open(config_buildout, "w") as fd:
                parser.write(fd)