Rename a virtualenv
773796
def rename_cmd(argv):
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('source')
    parser.add_argument('target')
    pargs = parser.parse_args(argv)
    copy_virtualenv_project(pargs.source, pargs.target)
    return rmvirtualenvs([pargs.source])
13060
def _setup_virtualenv():
    
    print("Downloading virtualenv...")
    import gzip, tarfile, io, tempfile, shutil
    tf = tarfile.open(fileobj=io.BytesIO(urlopen(VIRTUALENV_URL).read()))
    temp_folder = tempfile.mkdtemp()
    tf.extractall(temp_folder)
    print("Calling virtualenv...")
    subprocess.call([sys.executable, os.path.join(temp_folder, 'virtualenv-1.10', 'virtualenv.py'), 
                     '--no-setuptools', '--no-pip', '--no-site-packages', os.path.join(os.curdir, 'venv')])
    shutil.rmtree(temp_folder)
755026
def rename(name, options={})
      result = @session.rename(path, name, options)
      @path = result.path.gsub(/^\//, '')
      return result
    end
1015799
def _virtualenv_sys(venv_path):
    ""
    executable = os.path.join(venv_path, env_bin_dir, 'python')
    # Must use "executable" as the first argument rather than as the
    # keyword argument "executable" to get correct value from sys.path
    p = subprocess.Popen([executable,
        '-c', 'import sys;'
              'print (sys.version[:3]);'
              'print ("\\n".join(sys.path));'],
        env={},
        stdout=subprocess.PIPE)
    stdout, err = p.communicate()
    assert not p.returncode and stdout
    lines = stdout.decode('utf-8').splitlines()
    return lines[0], list(filter(bool, lines[1:]))
516959
def set_name(self, new_name):
        

        # change the hostname in the startup-config
        if os.path.isfile(self.startup_config_path):
            try:
                with open(self.startup_config_path, "r+", encoding="utf-8", errors="replace") as f:
                    old_config = f.read()
                    new_config = re.sub(r"^hostname .+$", "hostname " + new_name, old_config, flags=re.MULTILINE)
                    f.seek(0)
                    f.write(new_config)
            except OSError as e:
                raise DynamipsError("Could not amend the configuration {}: {}".format(self.startup_config_path, e))

        # change the hostname in the private-config
        if os.path.isfile(self.private_config_path):
            try:
                with open(self.private_config_path, "r+", encoding="utf-8", errors="replace") as f:
                    old_config = f.read()
                    new_config = old_config.replace(self.name, new_name)
                    f.seek(0)
                    f.write(new_config)
            except OSError as e:
                raise DynamipsError("Could not amend the configuration {}: {}".format(self.private_config_path, e))

        yield from self._hypervisor.send('vm rename "{name}" "{new_name}"'.format(name=self._name, new_name=new_name))
        log.info('Router "{name}" [{id}]: renamed to "{new_name}"'.format(name=self._name, id=self._id, new_name=new_name))
        self._name = new_name
559978
def restore_cmd(argv):
    """"""

    if len(argv) < 1:
        sys.exit('You must provide a valid virtualenv to target')

    env = argv[0]
    path = workon_home / env
    py = path / env_bin_dir / ('python.exe' if windows else 'python')
    exact_py = py.resolve().name

    return check_call([sys.executable, "-m", "virtualenv", str(path.absolute()), "--python=%s" % exact_py])
107139
def get_virtualenv_path(ve_base, ve_name):
    
    if not ve_base:
        raise exceptions.NoVirtualenvsDirectory(
            "could not figure out a virtualenvs directory. "
            "make sure $HOME is set, or $WORKON_HOME,"
            " or set virtualenvs=something in your .vexrc")

    # Using this requires get_ve_base to pass through nonexistent dirs
    if not os.path.exists(ve_base):
        message = (
            "virtualenvs directory {0!r} not found. "
            "Create it or use vex --make to get started."
        ).format(ve_base)
        raise exceptions.NoVirtualenvsDirectory(message)

    if not ve_name:
        raise exceptions.InvalidVirtualenv("no virtualenv name")

    # n.b.: if ve_name is absolute, ve_base is discarded by os.path.join,
    # and an absolute path will be accepted as first arg.
    # So we check if they gave an absolute path as ve_name.
    # But we don't want this error if $PWD == $WORKON_HOME,
    # in which case 'foo' is a valid relative path to virtualenv foo.
    ve_path = os.path.join(ve_base, ve_name)
    if ve_path == ve_name and os.path.basename(ve_name) != ve_name:
        raise exceptions.InvalidVirtualenv(
            'To run in a virtualenv by its path, '
            'use "vex --path {0}"'.format(ve_path))

    ve_path = os.path.abspath(ve_path)
    if not os.path.exists(ve_path):
        raise exceptions.InvalidVirtualenv(
            "no virtualenv found at {0!r}.".format(ve_path))
    return ve_path
1095215
def rm(venv_name):
    
    inenv = InenvManager()
    venv = inenv.get_venv(venv_name)
    click.confirm("Delete dir {}".format(venv.path))
    shutil.rmtree(venv.path)
175386
def create_env(self, interpreter, is_current, options):
        """"""
        if is_current:
            # apply pyvenv options
            pyvenv_options = options['pyvenv_options']
            if "--system-site-packages" in pyvenv_options:
                self.system_site_packages = True
            logger.debug("Creating virtualenv with pyvenv. options=%s", pyvenv_options)
            self.create(self.env_path)
        else:
            virtualenv_options = options['virtualenv_options']
            logger.debug("Creating virtualenv with virtualenv")
            self.create_with_virtualenv(interpreter, virtualenv_options)
        logger.debug("env_bin_path: %s", self.env_bin_path)

        # Re check if pip was installed (supporting both binary and .exe for Windows)
        pip_bin = os.path.join(self.env_bin_path, "pip")
        pip_exe = os.path.join(self.env_bin_path, "pip.exe")
        if not (os.path.exists(pip_bin) or os.path.exists(pip_exe)):
            logger.debug("pip isn't installed in the venv, setting pip_installed=False")
            self.pip_installed = False

        return self.env_path, self.env_bin_path, self.pip_installed
902484
def root(venv_name):
    """"""
    inenv = InenvManager()
    inenv.get_venv(venv_name)
    venv = inenv.registered_venvs[venv_name]
    click.secho(venv['root'])
888957
def venv_bin(name=None):  # pylint: disable=inconsistent-return-statements
    
    if not hasattr(sys, "real_prefix"):
        easy.error("ERROR: '%s' is not a virtualenv" % (sys.executable,))
        sys.exit(1)

    for bindir in ("bin", "Scripts"):
        bindir = os.path.join(sys.prefix, bindir)
        if os.path.exists(bindir):
            if name:
                bin_ext = os.path.splitext(sys.executable)[1] if sys.platform == 'win32' else ''
                return os.path.join(bindir, name + bin_ext)
            else:
                return bindir

    easy.error("ERROR: Scripts directory not found in '%s'" % (sys.prefix,))
    sys.exit(1)
1241793
def _build_env(venv_dir):
    
    # NB: We had to create the because the venv modules wasn't doing what we
    # needed. In particular, if we used it create a venv from an existing venv,
    # it *always* created symlinks back to the original venv's python
    # executables. Then, when you used those linked executables, you ended up
    # interacting with the original venv. I could find no way around this, hence
    # this function.
    prefix = getattr(sys, 'real_prefix', sys.prefix)
    python = Path(prefix) / 'bin' / 'python'
    command = '{} -m venv {}'.format(python, venv_dir)
    try:
        log.info('Creating virtual environment: %s', command)
        subprocess.run(command.split(),
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT,
                       check=True)
    except subprocess.CalledProcessError as exc:
        log.error("Error creating virtual environment: %s", exc.output)
        raise
651916
def reset(name):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.reset',
                [name],
                timeout=600)
        for comp in cmd_ret:
            ret.update(comp)
        __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress')
    except SaltClientError as client_error:
        print(client_error)
    return ret
1121707
def switch_or_run(cmd, venv_name=None):
    """"""
    if cmd:
        return _run(venv_name, cmd)
    inenv = InenvManager()
    if not os.getenv(INENV_ENV_VAR):
        activator_warn(inenv)
        return
    else:
        venv = inenv.get_prepped_venv(venv_name)
        inenv.clear_extra_source_file()
        inenv.write_extra_source_file("source {}".format(venv.activate_shell_file))
        inenv.write_extra_source_file(override_envars_and_deactivate(inenv.get_envvars(venv_name)))
        if autojump_enabled():
            directory = inenv.guess_contents_dir(venv_name)
            inenv.write_extra_source_file('cd {}'.format(directory))
            click.secho("Jumping to {}".format(directory), fg='green')
        sys.exit(EVAL_EXIT_CODE)
139474
def rename(name, new_name):
    '''
    
    '''
    current_info = info(name)
    if not current_info:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
    new_info = info(new_name)
    if new_info:
        raise CommandExecutionError(
            'User \'{0}\' already exists'.format(new_name)
        )
    cmd = ['pw', 'usermod', '-l', new_name, '-n', name]
    __salt__['cmd.run'](cmd)
    post_info = info(new_name)
    if post_info['name'] != current_info['name']:
        return post_info['name'] == new_name
    return False
1150390
def change_env(name, val):
    
    oldval = os.environ.get(name, None)
    os.environ[name] = val
    yield
    if oldval is None:
        del os.environ[name]
    else:
        os.environ[name] = oldval
1215581
def rename(src, dst):
    '''
    
    '''
    src = os.path.expanduser(src)
    dst = os.path.expanduser(dst)

    if not os.path.isabs(src):
        raise SaltInvocationError('File path must be absolute.')

    try:
        os.rename(src, dst)
        return True
    except OSError:
        raise CommandExecutionError(
            'Could not rename \'{0}\' to \'{1}\''.format(src, dst)
        )
    return False