Commits

Vinay Sajip committed 9fa5b9d Merge

Merged upstream changes.

Comments (0)

Files changed (36)

 syntax: glob
+*~
 *.pyc
 README.html
 build
 tests/testpackage/build
 tests/testpackage/dist
 tests/testpackage/testpackage.egg-info
+tests/testtemplate/build
+tests/testtemplate/dist
+tests/testtemplate/testtemplate.egg-info
 trace.txt
 virtualenvwrapper.egg-info
 virtualenvwrapper/docs
 246ce68795ea9caeb88ec2fa17e4f3151c58cf3f 2.6.3
 ea378ef00313cd77d251e61b4c0422503972b79f 2.7
 b20cf787d8e1c167853709ca01731a3efb4b5fe8 2.7.1
+7e0abe005937033aaf5d00fe3db3c94addecef7b 2.8
+7e0abe005937033aaf5d00fe3db3c94addecef7b 2.8
+279244c0fa41a327cc534fc40e9e7fadea180c23 2.8
+9e10c201a5005cc2d6c6728dfb0cda56deb4339d 2.10.1
 
 virtualenvwrapper is tested under Python 2.4 - 2.7.
 
+Upgrading to 2.9
+================
+
+Version 2.9 includes the features previously delivered separately by
+``virtualenvwrapper.project``.  If you have an older verison of the
+project extensions installed, remove them before upgrading.
+
 Upgrading from 1.x
 ==================
 
 *without* your aliases enabled.  If you can identify the alias causing
 the problem, that will help make virtualenvwrapper more robust.
 
+==========
+Change Log
+==========
+
+The `release history`_ is part of the project documentation.
+
+.. _release history: http://www.doughellmann.com/docs/virtualenvwrapper/history.html
+
 =======
 License
 =======
-=========================
- virtualenvwrapper 2.7.1
-=========================
+==========================
+ virtualenvwrapper 2.10.1
+==========================
 
 What is virtualenvwrapper
 =========================
 making it easier to work on more than one project at a time without
 introducing conflicts in their dependencies.
 
-What's New in 2.7.1
-===================
+What's New in 2.10.1
+====================
 
-This release includes a fix for a minor intialization problem in 2.7
-and updated installization instructions for first-time users.
+This bug-fix release includes a change to ``mktmpenv`` to resolve a
+problem with the way command line arguments were being handled. All
+temporary environments are now given automatically-generated names and
+the ability to name a temporary environment has been removed.
+
+Installing
+==========
+
+Visit the virtualenvwrapper_ project page for download links and
+installation instructions.
 
 .. _virtualenv: http://pypi.python.org/pypi/virtualenv
 

docs/en/command_ref.rst

 
 Syntax::
 
-    mkvirtualenv [options] ENVNAME
+    mkvirtualenv [-i package] [-r requirements_file] [virtualenv options] ENVNAME
 
-All command line options are passed directly to ``virtualenv``.  The
-new environment is automatically activated after being initialized.
+All command line options except ``-i``, ``-r``, and ``-h`` are passed
+directly to ``virtualenv``.  The new environment is automatically
+activated after being initialized.
 
 ::
 
     mynewenv
     (mynewenv)$ 
 
+The ``-i`` option can be used to install one or more packages (by
+repeating the option) after the environment is created.
+
+The ``-r`` option can be used to specify a text file listing packages
+to be installed. The argument value is passed to ``pip -r`` to be
+installed.
+
 .. seealso::
 
    * :ref:`scripts-premkvirtualenv`
    * :ref:`scripts-postmkvirtualenv`
+   * `requirements file format`_
+
+.. _requirements file format: http://www.pip-installer.org/en/latest/requirement-format.html
+
+.. _command-mktmpenv:
+
+mktmpenv
+--------
+
+Create a new virtualenv in the ``WORKON_HOME`` directory.
+
+Syntax::
+
+    mktmpenv [VIRTUALENV_OPTIONS]
+
+A unique virtualenv name is generated.
+
+::
+
+    $ mktmpenv
+    Using real prefix '/Library/Frameworks/Python.framework/Versions/2.7'
+    New python executable in 1e513ac6-616e-4d56-9aa5-9d0a3b305e20/bin/python
+    Overwriting 1e513ac6-616e-4d56-9aa5-9d0a3b305e20/lib/python2.7/distutils/__init__.py 
+    with new content
+    Installing distribute...............................................
+    ....................................................................
+    .................................................................done.
+    This is a temporary environment. It will be deleted when deactivated.
+    (1e513ac6-616e-4d56-9aa5-9d0a3b305e20) $
 
 .. _command-lsvirtualenv:
 
     Enabled global site-packages
     (env1)$ toggleglobalsitepackages -q
     (env1)$
+
+============================
+Project Directory Management
+============================
+
+.. seealso::
+
+   :ref:`project-management`
+
+.. _command-mkproject:
+
+mkproject
+---------
+
+Create a new virtualenv in the WORKON_HOME and project directory in
+PROJECT_HOME.
+
+Syntax::
+
+    mkproject [-t template] [virtualenv_options] ENVNAME
+
+The template option may be repeated to have several templates used to
+create a new project.  The templates are applied in the order named on
+the command line.  All other options are passed to ``mkvirtualenv`` to
+create a virtual environment with the same name as the project.
+
+::
+
+    $ mkproject myproj
+    New python executable in myproj/bin/python
+    Installing distribute.............................................
+    ..................................................................
+    ..................................................................
+    done.
+    Creating /Users/dhellmann/Devel/myproj
+    (myproj)$ pwd
+    /Users/dhellmann/Devel/myproj
+    (myproj)$ echo $VIRTUAL_ENV
+    /Users/dhellmann/Envs/myproj
+    (myproj)$ 
+
+.. seealso::
+
+  * :ref:`scripts-premkproject`
+  * :ref:`scripts-postmkproject`
+
+setvirtualenvproject
+--------------------
+
+Bind an existing virtualenv to an existing project.
+
+Syntax::
+
+  setvirtualenvproject [virtualenv_path project_path]
+
+The arguments to ``setvirtualenvproject`` are the full paths to the
+virtualenv and project directory.  An association is made so that when
+``workon`` activates the virtualenv the project is also activated.
+
+::
+
+    $ mkproject myproj
+    New python executable in myproj/bin/python
+    Installing distribute.............................................
+    ..................................................................
+    ..................................................................
+    done.
+    Creating /Users/dhellmann/Devel/myproj
+    (myproj)$ mkvirtualenv myproj_new_libs
+    New python executable in myproj/bin/python
+    Installing distribute.............................................
+    ..................................................................
+    ..................................................................
+    done.
+    Creating /Users/dhellmann/Devel/myproj
+    (myproj_new_libs)$ setvirtualenvproject $VIRTUAL_ENV $(pwd)
+
+When no arguments are given, the current virtualenv and current
+directory are assumed.
+
+Any number of virtualenvs can refer to the same project directory,
+making it easy to switch between versions of Python or other
+dependencies for testing.
+
+.. _command-cdproject:
+
+cdproject
+---------
+
+Change the current working directory to the one specified as the
+project directory for the active virtualenv.
+
+Syntax::
+
+  cdproject
+

docs/en/developers.rst

 .. _shunit2: http://shunit2.googlecode.com/
 
 .. _tox: http://codespeak.net/tox
+
+.. _developer-templates:
+
+Creating a New Template
+=======================
+
+virtualenvwrapper.project templates work like `virtualenvwrapper
+plugins
+<http://www.doughellmann.com/docs/virtualenvwrapper/plugins.html>`__.
+The *entry point* group name is
+``virtualenvwrapper.project.template``.  Configure your entry point to
+refer to a function that will **run** (source hooks are not supported
+for templates).
+
+The argument to the template function is the name of the project being
+created.  The current working directory is the directory created to
+hold the project files (``$PROJECT_HOME/$envname``).
+
+Help Text
+---------
+
+One difference between project templates and other virtualenvwrapper
+extensions is that only the templates specified by the user are run.
+The ``mkproject`` command has a help option to give the user a list of
+the available templates.  The names are taken from the registered
+entry point names, and the descriptions are taken from the docstrings
+for the template functions.

docs/en/extensions.rst

 Below is a list of some of the extensions available for use with
 virtualenvwrapper.
 
-.. _extensions-user_scripts:
-
-project
-=======
-
-The project_ extension adds development directory management with
-templates to virtualenvwrapper.
-
-bitbucket
----------
-
-The bitbucket_ project template creates a working directory and
-automatically clones the repository from BitBucket.  Requires
-project_.
-
-.. _project: http://www.doughellmann.com/projects/virtualenvwrapper.project/
-
-.. _bitbucket: http://www.doughellmann.com/projects/virtualenvwrapper.bitbucket/
-
 emacs-desktop
 =============
 
 
 .. _emacs-desktop: http://www.doughellmann.com/projects/virtualenvwrapper-emacs-desktop/
 
+.. _extensions-user_scripts:
+
 user_scripts
 ============
 
 activate based on the name of the file being edited.
 
 .. _vim-virtualenv: https://github.com/jmcantrell/vim-virtualenv
+
+.. _extensions-templates:
+
+Templates
+=========
+
+Below is a list of some of the templates available for use with
+:ref:`command-mkproject`.
+
+.. _templates-bitbucket:
+
+bitbucket
+---------
+
+The bitbucket_ extension automatically clones a mercurial repository
+from the specified bitbucket project.
+
+.. _bitbucket: http://www.doughellmann.com/projects/virtualenvwrapper.bitbucket/
+
+.. _templates-django:
+
+django
+------
+
+The django_ extension automatically creates a new Django project.
+
+.. _django: http://www.doughellmann.com/projects/virtualenvwrapper.django/
+
+.. seealso::
+
+   * :ref:`developer-templates`

docs/en/history.rst

 Release History
 ===============
 
+2.10.1
+
+  - Changed arguments to :ref:`command-mktmpenv` so it always creates
+    an environment name for you. (:bbissue:`114` reported by
+    :bbuser:`alex_gaynor`)
+
+2.10
+
+  - Incorporated patch to add ``-d`` option to
+    :ref:`command-add2virtualenv`, contributed by :bbuser:`miracle2k`.
+  - Add ``-i`` option to :ref:`command-mkvirtualenv`.
+  - Add :ref:`command-mktmpenv` command for creating temporary
+    environments that are automatically removed when they are
+    deactivated.
+  - Fixed a problem with hook_loader that prevented it from working
+    under Python 2.5 and 2.4.
+  - Fix a problem with the way template names were processed under
+    zsh. (:bbissue:`111`)
+
+2.9
+
+  - Change the shell function shell definition syntax so that ksh will
+    treat typeset-declared variables as local. No kidding.
+  - Merge the "project directory" features of the
+    ``virtualenvwrapper.project`` plugin into the main project, adding
+    :ref:`command-mkproject`, :ref:`command-cdproject`, and
+    :ref:`command-setvirtualenvproject` commands.
+  - Add ``-r`` option to :ref:`command-mkvirtualenv` to install
+    dependencies using a pip requirements file.
+
+2.8
+
+  - Use VIRTUALENVWRAPPER_VIRTUALENV in `cpvirtualenv` (:bbissue:`104`).
+  - Add support for `MSYS <http://www.mingw.org/wiki/MSYS>`_
+    environment under Windows. Contributed by Axel
+    H. (:bbuser:`noirbizarre`).
+
 2.7.2
 
   - Move setup code for tab completion later in the startup code so

docs/en/index.rst

    install
    command_ref
    hooks
+   projects
    tips
    developers
    extensions

docs/en/install.rst

 ================
 
 virtualenvwrapper is a set of shell *functions* defined in Bourne
-shell compatible syntax.  It is tested under `bash`, `ksh`, and `zsh`.
+shell compatible syntax.  Its automated tests run under these
+shells on OS X and Linux:
+
+* ``bash``
+* ``ksh``
+* ``zsh``
+
 It may work with other shells, so if you find that it does work with a
 shell not listed here please let me know.  If you can modify it to
-work with another shell, without completely rewriting it, send a pull
-request through the bitbucket project page.  If you write a clone to
+work with another shell without completely rewriting it, then send a pull
+request through the `bitbucket project page`_.  If you write a clone to
 work with an incompatible shell, let me know and I will link to it
 from this page.
 
+.. _bitbucket project page: https://bitbucket.org/dhellmann/virtualenvwrapper/
+
+MSYS
+----
+
+It is possible to use virtualenv wrapper under `MSYS
+<http://www.mingw.org/wiki/MSYS>`_ with a native Windows Python
+installation.  In order to make it work, you need to define an extra
+environment variable named ``MSYS_HOME`` containing the root path to
+the MSYS installation.
+
+::
+
+    export WORKON_HOME=$HOME/.virtualenvs
+    export MSYS_HOME=/c/msys/1.0
+    source /usr/local/bin/virtualenvwrapper.sh
+
+or::
+
+    export WORKON_HOME=$HOME/.virtualenvs
+    export MSYS_HOME=C:\msys\1.0
+    source /usr/local/bin/virtualenvwrapper.sh
+
+Depending on your MSYS setup, you may need to install the `MSYS mktemp
+binary`_ in the ``MSYS_HOME/bin`` folder.
+
+.. _MSYS mktemp binary: http://sourceforge.net/projects/mingw/files/MSYS/mktemp/
+
+PowerShell
+----------
+
+Guillermo López-Anglada has ported virtualenvwrapper to run under
+Microsoft's PowerShell. We have agreed that since it is not compatible
+with the rest of the extensions, and is largely a re-implementation
+(rather than an adaptation), it should be distributed separately. You
+can download virtualenvwrapper-powershell_ from PyPI.
+
+.. _virtualenvwrapper-powershell: http://pypi.python.org/pypi/virtualenvwrapper-powershell/2.7.1
+
 .. _supported-versions:
 
 Python Versions
 Shell Startup File
 ==================
 
-Add two lines to your shell startup file (``.bashrc``, ``.profile``,
-etc.) to set the location where the virtual environments should live
-and the location of the script installed with this package::
+Add three lines to your shell startup file (``.bashrc``, ``.profile``,
+etc.) to set the location where the virtual environments should live,
+the location of your development project directorkes, and the location
+of the script installed with this package::
 
     export WORKON_HOME=$HOME/.virtualenvs
+    export PROJECT_HOME=$HOME/Devel
     source /usr/local/bin/virtualenvwrapper.sh
 
 After editing it, reload the startup file (e.g., run ``source
 variables. Set the variables in your shell startup file *before*
 loading ``virtualenvwrapper.sh``.
 
+.. _variable-WORKON_HOME:
+
 Location of Environments
 ------------------------
 
 the directory does not exist when virtualenvwrapper is loaded, it will
 be created automatically.
 
+.. _variable-PROJECT_HOME:
+
+Location of Project Directories
+-------------------------------
+
+The variable ``PROJECT_HOME`` tells virtualenvwrapper where to place
+your project working directories.  The variable must be set and the
+directory created before :ref:`command-mkproject` is used.
+
+.. seealso::
+
+   * :ref:`project-management`
+
 .. _variable-VIRTUALENVWRAPPER_HOOK_DIR:
 
 Location of Hook Scripts
 where the :ref:`user-defined hooks <scripts>` should be placed. The
 default is ``$WORKON_HOME``.
 
+.. seealso::
+
+   * :ref:`scripts`
+
 .. _variable-VIRTUALENVWRAPPER_LOG_DIR:
 
 Location of Hook Logs
 cannot disable it. Refer to the documentation for the shell to
 identify the appropriate file to edit.
 
+Upgrading to 2.9
+================
+
+Version 2.9 includes the features previously delivered separately by
+``virtualenvwrapper.project``.  If you have an older verison of the
+project extensions installed, remove them before upgrading.
+
 Upgrading from 1.x
 ==================
 

docs/en/projects.rst

+.. _project-management:
+
+====================
+ Project Management
+====================
+
+A :term:`project directory` is associated with a virtualenv, but
+usually contains the source code under active development rather than
+the installed components needed to support the development. For
+example, the project directory may contain the source code checked out
+from a version control system, temporary artifacts created by testing,
+experimental files not committed to version control, etc.
+
+A project directory is created and bound to a virtualenv when
+:ref:`command-mkproject` is run instead of
+:ref:`command-mkvirtualenv`. To bind an existing project directory to
+a virtualenv, use :ref:`command-setvirtualenvproject`.
+
+Using Templates
+===============
+
+A new project directory can be created empty, or populated using one
+or more :term:`template` plugins. Templates should be specified as
+arguments to :ref:`command-mkproject`. Multiple values can be provided
+to apply more than one template. For example, to check out a Mercurial
+repository from on a project on bitbucket and create a new Django
+site, combine the :ref:`templates-bitbucket` and
+:ref:`templates-django` templates.
+
+::
+
+    $ mkproject -t bitbucket -t django my_site
+
+.. seealso::
+
+   * :ref:`extensions-templates`

docs/en/scripts.rst

 The ``$VIRTUALENVWRAPPER_HOOK_DIR/postrmvirtualenv`` script is run as an external
 program after the environment is removed. The full path to the
 environment directory is passed as an argument to the script.
+
+.. _scripts-premkproject:
+
+premkproject
+===============
+
+  :Global/Local: global
+  :Argument(s): name of new project
+  :Sourced/Run: run
+
+``$WORKON_HOME/premkproject`` is run as an external program after the
+virtual environment is created and after the current environment is
+switched to point to the new env, but before the new project directory
+is created. The current working directory for the script is
+``$PROJECT_HOME`` and the name of the new project is passed as an
+argument to the script.
+
+.. _scripts-postmkproject:
+
+postmkproject
+================
+
+  :Global/Local: global
+  :Argument(s): none
+  :Sourced/Run: sourced
+
+``$WORKON_HOME/postmkproject`` is sourced after the new environment
+and project directories are created and the virtualenv is activated.
+The current working directory is the project directory.

docs/sphinx/conf.py

 # serve to show the default.
 
 import sys, os
+import subprocess
 
 # If extensions (or modules to document with autodoc) are in another directory,
 # add these directories to sys.path here. If the directory is relative to the
 # built documents.
 #
 # The short X.Y version.
-version = '2.7.1'
+version = subprocess.check_output(['sh', '-c', 'cd ../..; python setup.py --version'])
+version = version.strip()
 # The full version, including alpha/beta/rc tags.
 release = version
 
 PROJECT = 'virtualenvwrapper'
 
 # Change docs/sphinx/conf.py too!
-VERSION = '2.7.1'
+VERSION = '2.10.1'
 
 # Bootstrap installation of Distribute
 import distribute_setup
 
     provides=['virtualenvwrapper',
               'virtualenvwrapper.user_scripts',
+              'virtualenvwrapper.project',
               ],
     install_requires=['virtualenv'],
 
         #'console_scripts': [ 'venvw_hook = virtualenvwrapper.hook_loader:main' ],
         'virtualenvwrapper.initialize': [
             'user_scripts = virtualenvwrapper.user_scripts:initialize',
+            'project = virtualenvwrapper.project:initialize',
             ],
         'virtualenvwrapper.initialize_source': [
             'user_scripts = virtualenvwrapper.user_scripts:initialize_source',
             'user_scripts = virtualenvwrapper.user_scripts:post_rmvirtualenv',
             ],
 
+        'virtualenvwrapper.project.pre_mkproject': [
+            'project = virtualenvwrapper.project:pre_mkproject',
+            ],
+        'virtualenvwrapper.project.post_mkproject_source': [
+            'project = virtualenvwrapper.project:post_mkproject_source',
+            ],
+
         'virtualenvwrapper.pre_activate': [
             'user_scripts = virtualenvwrapper.user_scripts:pre_activate',
             ],
         'virtualenvwrapper.post_activate_source': [
             'user_scripts = virtualenvwrapper.user_scripts:post_activate_source',
+            'project = virtualenvwrapper.project:post_activate_source',
             ],
 
         'virtualenvwrapper.pre_deactivate_source': [
 
 # Run the test scripts with a little formatting around them to make it
 # easier to find where each script output starts.
-for test_shell in bash ksh zsh
+for test_script in $scripts
 do
-    test_shell_opts=
-    if [ $test_shell = "zsh" ]; then
-        test_shell_opts="-o shwordsplit"
-    fi
-    test_shell=$(which $test_shell)
 
-    for test_script in $scripts
+    for test_shell in bash ksh zsh
     do
+	test_shell_opts=
+	if [ $test_shell = "zsh" ]; then
+            test_shell_opts="-o shwordsplit"
+	fi
+	export test_shell=$(which $test_shell)
+
         echo
         echo '********************************************************************************'
         echo "Running $test_script"
 }
 
 test_virtualenvwrapper_initialize() {
-    virtualenvwrapper_initialize
+    assertTrue "Initialized" virtualenvwrapper_initialize
     for hook in premkvirtualenv postmkvirtualenv prermvirtualenv postrmvirtualenv preactivate postactivate predeactivate postdeactivate
     do
-        assertTrue "Global $hook was not created" "[ -f $WORKON_HOME/$hook ]"
-        assertTrue "Global $hook is not executable" "[ -x $WORKON_HOME/$hook ]"
+        assertTrue "Global $WORKON_HOME/$hook was not created" "[ -f $WORKON_HOME/$hook ]"
+        assertTrue "Global $WORKON_HOME/$hook is not executable" "[ -x $WORKON_HOME/$hook ]"
     done
     assertTrue "Log file was not created" "[ -f $WORKON_HOME/hook.log ]"
     export pre_test_dir=$(cd "$test_dir"; pwd)
     cd "$WORKON_HOME"
     mkvirtualenv --no-site-packages no_wrappers
     expected="ImportError: No module named virtualenvwrapper.hook_loader"
-    output=$(VIRTUALENVWRAPPER_PYTHON=$(which python) $SHELL $return_to/virtualenvwrapper.sh 2>&1)
-    echo "$output" | grep -q "$expected" 2>&1
-    found=$?
-    assertTrue "Expected \"$expected\", got: \"$output\"" "[ $found -eq 0 ]"
+    # test_shell is set by tests/run_tests
+    if [ "$test_shell" = "" ]
+    then
+	export test_shell=$SHELL
+    fi
+    subshell_output=$(VIRTUALENVWRAPPER_PYTHON="$WORKON_HOME/no_wrappers/bin/python" $test_shell $return_to/virtualenvwrapper.sh 2>&1)
+    echo "$subshell_output"
+    echo "$subshell_output" | grep -q "$expected" 2>&1
+    found_it=$?
+    echo "$found_it"
+    assertTrue "Expected \'$expected\', got: \'$subshell_output\'" "[ $found_it -eq 0 ]"
     assertFalse "Failed to detect invalid Python location" "VIRTUALENVWRAPPER_PYTHON=$VIRTUAL_ENV/bin/python $SHELL $return_to/virtualenvwrapper.sh >/dev/null 2>&1"
     cd "$return_to"
     deactivate

tests/test_add2virtualenv.sh

 }
 
 test_add2virtualenv () {
-    mkvirtualenv "pathtest"
-    add2virtualenv "/full/path"
+    mkvirtualenv "pathtest" >/dev/null 2>&1
+    full_path=$(pwd)
+    add2virtualenv "$full_path"
     cdsitepackages
-    path_file="./virtualenv_path_extensions.pth"
-    assertTrue "No /full/path in `cat $path_file`" "grep /full/path $path_file"
-    cd -
+    # Check contents of path file
+    path_file="./_virtualenv_path_extensions.pth"
+    assertTrue "No $full_path in $(cat $path_file)" "grep -q $full_path $path_file"
+    assertTrue "No path insert code in $(cat $path_file)" "grep -q sys.__egginsert $path_file"
+    # Check the path we inserted is actually at the top
+    expected="$full_path"
+    actual=$($WORKON_HOME/pathtest/bin/python -c "import sys; print sys.path[1]")
+    assertSame "$expected" "$actual"
+    # Make sure the temporary file created
+    # during the edit was removed
+    assertFalse "Temporary file ${path_file}.tmp still exists" "[ -f ${path_file}.tmp ]"
+    cd - >/dev/null 2>&1
 }
 
 test_add2virtualenv_relative () {
-    mkvirtualenv "pathtest"
+    mkvirtualenv "pathtest" >/dev/null 2>&1
     parent_dir=$(dirname $(pwd))
     base_dir=$(basename $(pwd))
     add2virtualenv "../$base_dir"
     cdsitepackages
-    path_file="./virtualenv_path_extensions.pth"
-    assertTrue "No $parent_dir/$base_dir in \"`cat $path_file`\"" "grep \"$parent_dir/$base_dir\" $path_file"
+    path_file="./_virtualenv_path_extensions.pth"
+    assertTrue "No $parent_dir/$base_dir in \"`cat $path_file`\"" "grep -q \"$parent_dir/$base_dir\" $path_file"
     cd - >/dev/null 2>&1
 }
 
+test_add2virtualenv_delete () {
+    path_file="./_virtualenv_path_extensions.pth"
+    mkvirtualenv "pathtest" >/dev/null 2>&1
+    cdsitepackages
+    # Make sure it was added
+    add2virtualenv "/full/path"
+    assertTrue "No $full_path in $(cat $path_file)" "grep -q $full_path $path_file"
+    # Remove it and verify that change
+    add2virtualenv -d "/full/path"
+    assertFalse "/full/path in `cat $path_file`" "grep -q /full/path $path_file"
+    cd - >/dev/null 2>&1
+}
+
 
 . "$test_dir/shunit2"
     assertTrue "$WORKON_HOME not in $VIRTUAL_ENV" "echo $VIRTUAL_ENV | grep -q $WORKON_HOME"
 }
 
+fake_virtualenv () {
+    typeset envname="$1"
+    touch "$envname/fake_virtualenv_was_here"
+    virtualenv $@
+}
+
+test_virtualenvwrapper_virtualenv_variable () {
+    mkvirtualenv "source"
+    export VIRTUALENVWRAPPER_VIRTUALENV=fake_virtualenv
+    cpvirtualenv "source" "destination"
+    unset VIRTUALENVWRAPPER_VIRTUALENV
+    assertTrue "wrapper was not run" "[ -f $VIRTUAL_ENV/fake_virtualenv_was_here ]"
+}
+
 test_source_relocatable () {
     mkvirtualenv "source"
     (cd tests/testpackage && python setup.py install) >/dev/null 2>&1
     rm -f "$WORKON_HOME/postmkvirtualenv"
 }
 
+test_no_site_packages () {
+    # See issue #102
+    mkvirtualenv "source" --no-site-packages >/dev/null 2>&1
+    cpvirtualenv "source" "destination"
+    ngsp_file="`virtualenvwrapper_get_site_packages_dir`/../no-global-site-packages.txt"
+    assertTrue "$ngsp_file does not exist in copied env" "[ -f \"$ngsp_file\" ]"
+}
+
+test_no_site_packages_default_args () {
+    # See issue #102
+    VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--no-site-packages"
+    # With the argument, verify that they are not copied.
+    mkvirtualenv "source" >/dev/null 2>&1
+    cpvirtualenv "source" "destination"
+    ngsp_file="`virtualenvwrapper_get_site_packages_dir`/../no-global-site-packages.txt"
+    assertTrue "$ngsp_file does not exist" "[ -f \"$ngsp_file\" ]"
+    unset VIRTUALENVWRAPPER_VIRTUALENV_ARGS
+}
+
 . "$test_dir/shunit2"
 

tests/test_dir_stack.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(cd $(dirname $0) && pwd)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+
+#unset HOOK_VERBOSE_OPTION
+
+setUp () {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+    mkdir "$WORKON_HOME/start_here"
+    mkdir "$WORKON_HOME/on_the_stack"
+    echo
+}
+
+tearDown() {
+    if type deactivate >/dev/null 2>&1
+    then 
+        deactivate
+    fi
+    rm -rf "$WORKON_HOME"
+}
+
+test_ticket_101 () {
+    mkvirtualenv some_env
+    deactivate
+    cd "$WORKON_HOME/start_here"
+    pushd "$WORKON_HOME/on_the_stack"
+    rmvirtualenv some_env
+    mkvirtualenv --no-site-packages some_env
+    #echo "After mkvirtualenv: `pwd`"
+    deactivate
+    #echo "After deactivate: `pwd`"
+    popd
+    #echo "After popd: `pwd`"
+    current_dir=$(pwd)
+    assertSame "$WORKON_HOME/start_here" "$current_dir"
+}
+
+. "$test_dir/shunit2"

tests/test_mktmpenv.sh

+#!/bin/sh
+
+test_dir=$(cd $(dirname $0) && pwd)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+}
+
+setUp () {
+    echo
+    rm -f "$test_dir/catch_output"
+}
+
+test_mktmpenv_no_name() {
+    before=$(lsvirtualenv -b)
+    mktmpenv >/dev/null 2>&1
+    after=$(lsvirtualenv -b)
+    assertFalse "Environment was not created" "[ \"$before\" = \"$after\" ]"
+}
+
+test_mktmpenv_name() {
+    mktmpenv name-given-by-user >/dev/null 2>&1
+    RC=$?
+    assertTrue "Error was not detected" "[ $RC -ne 0 ]"
+}
+
+test_mktmpenv_virtualenv_args() {
+    mktmpenv --no-site-packages >/dev/null 2>&1
+    ngsp_file="`virtualenvwrapper_get_site_packages_dir`/../no-global-site-packages.txt"
+    assertTrue "$ngsp_file does not exist" "[ -f \"$ngsp_file\" ]"
+}
+
+test_deactivate() {
+    mktmpenv >/dev/null 2>&1
+    assertTrue "Environment was not created" "[ ! -z \"$VIRTUAL_ENV\" ]"
+    env_name=$(basename "$VIRTUAL_ENV")
+    deactivate >/dev/null 2>&1
+    assertFalse "Environment still exists" "[ -d \"$WORKON_HOME/$env_name\" ]"
+}
+
+. "$test_dir/shunit2"

tests/test_mkvirtualenv.sh

 }
 
 test_mkvirtualenv_args () {
+    # See issue #102
     VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--no-site-packages"
     # With the argument, verify that they are not copied.
     mkvirtualenv "without_sp2" >/dev/null 2>&1

tests/test_mkvirtualenv_install.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(cd $(dirname $0) && pwd)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+    rm -f "$test_dir/requirements.txt"
+}
+
+setUp () {
+    echo
+    rm -f "$test_dir/catch_output"
+}
+
+test_single_package () {
+    mkvirtualenv -i commandlineapp "env4" >/dev/null 2>&1
+    installed=$(pip freeze)
+    assertTrue "CommandLineApp not found in $installed" "echo $installed | grep CommandLineApp"
+}
+
+test_multiple_packages () {
+    mkvirtualenv -i commandlineapp -i csvcat "env4" >/dev/null 2>&1
+    installed=$(pip freeze)
+    assertTrue "CommandLineApp not found in $installed" "echo $installed | grep CommandLineApp"
+    assertTrue "csvcat not found in $installed" "echo $installed | grep csvcat"
+}
+
+. "$test_dir/shunit2"

tests/test_mkvirtualenv_requirements.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(cd $(dirname $0) && pwd)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+    rm -f "$test_dir/requirements.txt"
+}
+
+setUp () {
+    echo
+    rm -f "$test_dir/catch_output"
+}
+
+test_requirements_file () {
+    echo "commandlineapp" > "$test_dir/requirements.txt"
+    mkvirtualenv -r "$test_dir/requirements.txt" "env3" >/dev/null 2>&1
+    installed=$(pip freeze)
+    assertTrue "CommandLineApp not found in $installed" "echo $installed | grep CommandLineApp"
+}
+
+. "$test_dir/shunit2"

tests/test_project.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(dirname $0)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+export PROJECT_HOME="$(echo ${TMPDIR:-/tmp}/PROJECT_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+    mkdir -p "$PROJECT_HOME"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+}
+
+setUp () {
+    echo
+    rm -f "$test_dir/catch_output"
+}
+
+test_initialize() {
+    source "$test_dir/../virtualenvwrapper.sh"
+    for hook in  premkproject postmkproject prermproject postrmproject
+    do
+        assertTrue "Global $hook was not created" "[ -f $WORKON_HOME/$hook ]"
+        assertTrue "Global $hook is not executable" "[ -x $WORKON_HOME/$hook ]"
+    done
+}
+
+test_initialize_hook_dir() {
+    export VIRTUALENVWRAPPER_HOOK_DIR="$WORKON_HOME/hooks"
+    mkdir -p "$VIRTUALENVWRAPPER_HOOK_DIR"
+    source "$test_dir/../virtualenvwrapper.sh"
+    for hook in  premkproject postmkproject prermproject postrmproject
+    do
+        assertTrue "Global $hook was not created" "[ -f $VIRTUALENVWRAPPER_HOOK_DIR/$hook ]"
+        assertTrue "Global $hook is not executable" "[ -x $VIRTUALENVWRAPPER_HOOK_DIR/$hook ]"
+    done
+    VIRTUALENVWRAPPER_HOOK_DIR="$WORKON_HOME"
+}
+
+test_virtualenvwrapper_verify_project_home() {
+    assertTrue "PROJECT_HOME not verified" virtualenvwrapper_verify_project_home
+}
+
+test_virtualenvwrapper_verify_project_home_missing_dir() {
+    old_home="$PROJECT_HOME"
+    PROJECT_HOME="$PROJECT_HOME/not_there"
+    assertFalse "PROJECT_HOME verified unexpectedly" virtualenvwrapper_verify_project_home
+    PROJECT_HOME="$old_home"
+}
+
+. "$test_dir/shunit2"

tests/test_project_activate.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(dirname $0)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+export PROJECT_HOME="$(echo ${TMPDIR:-/tmp}/PROJECT_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+    mkdir -p "$PROJECT_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+# oneTimeTearDown() {
+#     rm -rf "$WORKON_HOME"
+#     rm -rf "$PROJECT_HOME"
+# }
+
+setUp () {
+    echo
+    rm -f "$TMPDIR/catch_output"
+}
+
+test_activate () {
+    mkproject myproject
+    deactivate
+    cd $TMPDIR
+    assertSame "" "$VIRTUAL_ENV"
+    workon myproject
+    assertSame "myproject" "$(basename $VIRTUAL_ENV)"
+    assertSame "$PROJECT_HOME/myproject" "$(pwd)"
+    deactivate
+}
+
+test_space_in_path () {
+    old_project_home="$PROJECT_HOME"
+    PROJECT_HOME="$PROJECT_HOME/with spaces"
+    mkdir -p "$PROJECT_HOME"
+    mkproject "myproject" >/dev/null 2>&1
+    deactivate
+    cd $TMPDIR
+    workon "myproject"
+    assertSame "myproject" "$(basename $VIRTUAL_ENV)"
+    assertSame "$PROJECT_HOME/myproject" "$(pwd)"
+    deactivate
+    PROJECT_HOME="$old_project_home"
+}
+
+
+. "$test_dir/shunit2"

tests/test_project_cd.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(dirname $0)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+export PROJECT_HOME="$(echo ${TMPDIR:-/tmp}/PROJECT_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+    mkdir -p "$PROJECT_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+}
+
+setUp () {
+    echo
+    rm -f "$TMPDIR/catch_output"
+}
+
+test_with_project () {
+    mkproject myproject >/dev/null 2>&1
+    cd $TMPDIR
+    cdproject
+    assertSame "$PROJECT_HOME/myproject" "$(pwd)"
+    deactivate
+}
+
+test_without_project () {
+    mkvirtualenv myproject >/dev/null 2>&1
+    cd $TMPDIR
+    output=$(cdproject 2>&1)
+    echo "$output" | grep -q "No project set"
+    RC=$?
+    assertSame "1" "$RC"
+    deactivate
+}
+
+test_space_in_path () {
+    old_project_home="$PROJECT_HOME"
+    PROJECT_HOME="$PROJECT_HOME/with spaces"
+    mkdir -p "$PROJECT_HOME"
+    mkproject "myproject" >/dev/null 2>&1
+    cd $TMPDIR
+    cdproject
+    assertSame "$PROJECT_HOME/myproject" "$(pwd)"
+    deactivate
+    PROJECT_HOME="$old_project_home"
+}
+
+
+. "$test_dir/shunit2"

tests/test_project_mk.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(dirname $0)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+export PROJECT_HOME="$(echo ${TMPDIR:-/tmp}/PROJECT_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+    mkdir -p "$PROJECT_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+}
+
+setUp () {
+    echo
+    rm -f "$WORKON_HOME/catch_output"
+}
+
+tearDown () {
+    type deactivate >/dev/null 2>&1 && deactivate
+}
+
+test_create_directories () {
+    mkproject myproject1 >/dev/null 2>&1
+    assertTrue "env directory not created" "[ -d $WORKON_HOME/myproject1 ]"
+    assertTrue "project directory not created" "[ -d $PROJECT_HOME/myproject1 ]"
+}
+
+test_create_virtualenv () {
+    mkproject myproject2 >/dev/null 2>&1
+    assertSame "myproject2" $(basename "$VIRTUAL_ENV")
+    assertSame "$PROJECT_HOME/myproject2" "$(cat $VIRTUAL_ENV/.project)"
+}
+
+test_hooks () {
+    echo "echo GLOBAL premkproject \`pwd\` \"\$@\" >> \"$WORKON_HOME/catch_output\"" >> "$VIRTUALENVWRAPPER_HOOK_DIR/premkproject"
+    chmod +x "$VIRTUALENVWRAPPER_HOOK_DIR/premkproject"
+    echo "echo GLOBAL postmkproject \`pwd\` >> $WORKON_HOME/catch_output" > "$VIRTUALENVWRAPPER_HOOK_DIR/postmkproject"
+
+    mkproject myproject3 >/dev/null 2>&1
+
+    output=$(cat "$WORKON_HOME/catch_output")
+
+    expected="GLOBAL premkproject $PROJECT_HOME myproject3
+GLOBAL postmkproject $PROJECT_HOME/myproject3"
+    assertSame "$expected" "$output"
+
+    rm -f "$VIRTUALENVWRAPPER_HOOK_DIR/premkproject"
+    rm -f "$VIRTUALENVWRAPPER_HOOK_DIR/postmkproject"
+}
+
+test_no_project_home () {
+    old_home="$PROJECT_HOME"
+    export PROJECT_HOME="$PROJECT_HOME/not_there"
+    output=`mkproject should_not_be_created 2>&1`
+    assertTrue "Did not see expected message" "echo $output | grep 'does not exist'"
+    PROJECT_HOME="$old_home"
+}
+
+test_project_exists () {
+    mkproject myproject4 >/dev/null 2>&1
+    output=`mkproject myproject4 2>&1`
+    assertTrue "Did not see expected message 'already exists' in: $output" "echo $output | grep 'already exists'"
+}
+
+test_same_workon_and_project_home () {
+    old_project_home="$PROJECT_HOME"
+    export PROJECT_HOME="$WORKON_HOME"
+    mkproject myproject5 >/dev/null 2>&1
+    assertTrue "env directory not created" "[ -d $WORKON_HOME/myproject1 ]"
+    assertTrue "project directory was created" "[ -d $old_project_home/myproject1 ]"
+    PROJECT_HOME="$old_project_home"
+}
+
+. "$test_dir/shunit2"

tests/test_project_templates.sh

+#!/bin/sh
+
+#set -x
+
+test_dir=$(dirname $0)
+
+export WORKON_HOME="$(echo ${TMPDIR:-/tmp}/WORKON_HOME | sed 's|//|/|g')"
+export PROJECT_HOME="$(echo ${TMPDIR:-/tmp}/PROJECT_HOME | sed 's|//|/|g')"
+
+oneTimeSetUp() {
+    (cd "$test_dir/testtemplate" && python setup.py install)
+    rm -rf "$WORKON_HOME"
+    mkdir -p "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+    mkdir -p "$PROJECT_HOME"
+    source "$test_dir/../virtualenvwrapper.sh"
+}
+
+oneTimeTearDown() {
+    rm -rf "$WORKON_HOME"
+    rm -rf "$PROJECT_HOME"
+}
+
+setUp () {
+    echo
+    rm -f "$TMPDIR/catch_output"
+}
+
+test_list_templates () {
+    output=$(mkproject -h 2>&1)
+    assertTrue "Did not find test template in \"$output\"" "echo \"$output\" | grep -q 'Creates a test file'"
+}
+
+test_apply_template () {
+    mkproject -t test proj1
+    assertTrue "Test file not created" "[ -f TEST_FILE ]"
+    assertTrue "project name not found" "grep -q proj1 TEST_FILE"
+}
+
+. "$test_dir/shunit2"

tests/testtemplate/distribute_setup.py

+#!python
+"""Bootstrap distribute installation
+
+If you want to use setuptools in your package's setup.py, just include this
+file in the same directory with it, and add this to the top of your setup.py::
+
+    from distribute_setup import use_setuptools
+    use_setuptools()
+
+If you want to require a specific version of setuptools, set a download
+mirror, or use an alternate download directory, you can do so by supplying
+the appropriate options to ``use_setuptools()``.
+
+This file can also be run as a script to install or upgrade setuptools.
+"""
+import os
+import sys
+import time
+import fnmatch
+import tempfile
+import tarfile
+from distutils import log
+
+try:
+    from site import USER_SITE
+except ImportError:
+    USER_SITE = None
+
+try:
+    import subprocess
+
+    def _python_cmd(*args):
+        args = (sys.executable,) + args
+        return subprocess.call(args) == 0
+
+except ImportError:
+    # will be used for python 2.3
+    def _python_cmd(*args):
+        args = (sys.executable,) + args
+        # quoting arguments if windows
+        if sys.platform == 'win32':
+            def quote(arg):
+                if ' ' in arg:
+                    return '"%s"' % arg
+                return arg
+            args = [quote(arg) for arg in args]
+        return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
+
+DEFAULT_VERSION = "0.6.10"
+DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
+SETUPTOOLS_FAKED_VERSION = "0.6c11"
+
+SETUPTOOLS_PKG_INFO = """\
+Metadata-Version: 1.0
+Name: setuptools
+Version: %s
+Summary: xxxx
+Home-page: xxx
+Author: xxx
+Author-email: xxx
+License: xxx
+Description: xxx
+""" % SETUPTOOLS_FAKED_VERSION
+
+
+def _install(tarball):
+    # extracting the tarball
+    tmpdir = tempfile.mkdtemp()
+    log.warn('Extracting in %s', tmpdir)
+    old_wd = os.getcwd()
+    try:
+        os.chdir(tmpdir)
+        tar = tarfile.open(tarball)
+        _extractall(tar)
+        tar.close()
+
+        # going in the directory
+        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
+        os.chdir(subdir)
+        log.warn('Now working in %s', subdir)
+
+        # installing
+        log.warn('Installing Distribute')
+        if not _python_cmd('setup.py', 'install'):
+            log.warn('Something went wrong during the installation.')
+            log.warn('See the error message above.')
+    finally:
+        os.chdir(old_wd)
+
+
+def _build_egg(egg, tarball, to_dir):
+    # extracting the tarball
+    tmpdir = tempfile.mkdtemp()
+    log.warn('Extracting in %s', tmpdir)
+    old_wd = os.getcwd()
+    try:
+        os.chdir(tmpdir)
+        tar = tarfile.open(tarball)
+        _extractall(tar)
+        tar.close()
+
+        # going in the directory
+        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
+        os.chdir(subdir)
+        log.warn('Now working in %s', subdir)
+
+        # building an egg
+        log.warn('Building a Distribute egg in %s', to_dir)
+        _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
+
+    finally:
+        os.chdir(old_wd)
+    # returning the result
+    log.warn(egg)
+    if not os.path.exists(egg):
+        raise IOError('Could not build the egg.')
+
+
+def _do_download(version, download_base, to_dir, download_delay):
+    egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
+                       % (version, sys.version_info[0], sys.version_info[1]))
+    if not os.path.exists(egg):
+        tarball = download_setuptools(version, download_base,
+                                      to_dir, download_delay)
+        _build_egg(egg, tarball, to_dir)
+    sys.path.insert(0, egg)
+    import setuptools
+    setuptools.bootstrap_install_from = egg
+
+
+def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
+                   to_dir=os.curdir, download_delay=15, no_fake=True):
+    # making sure we use the absolute path
+    to_dir = os.path.abspath(to_dir)
+    was_imported = 'pkg_resources' in sys.modules or \
+        'setuptools' in sys.modules
+    try:
+        try:
+            import pkg_resources
+            if not hasattr(pkg_resources, '_distribute'):
+                if not no_fake:
+                    _fake_setuptools()
+                raise ImportError
+        except ImportError:
+            return _do_download(version, download_base, to_dir, download_delay)
+        try:
+            pkg_resources.require("distribute>="+version)
+            return
+        except pkg_resources.VersionConflict:
+            e = sys.exc_info()[1]
+            if was_imported:
+                sys.stderr.write(
+                "The required version of distribute (>=%s) is not available,\n"
+                "and can't be installed while this script is running. Please\n"
+                "install a more recent version first, using\n"
+                "'easy_install -U distribute'."
+                "\n\n(Currently using %r)\n" % (version, e.args[0]))
+                sys.exit(2)
+            else:
+                del pkg_resources, sys.modules['pkg_resources']    # reload ok
+                return _do_download(version, download_base, to_dir,
+                                    download_delay)
+        except pkg_resources.DistributionNotFound:
+            return _do_download(version, download_base, to_dir,
+                                download_delay)
+    finally:
+        if not no_fake:
+            _create_fake_setuptools_pkg_info(to_dir)
+
+def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
+                        to_dir=os.curdir, delay=15):
+    """Download distribute from a specified location and return its filename
+
+    `version` should be a valid distribute version number that is available
+    as an egg for download under the `download_base` URL (which should end
+    with a '/'). `to_dir` is the directory where the egg will be downloaded.
+    `delay` is the number of seconds to pause before an actual download
+    attempt.
+    """
+    # making sure we use the absolute path
+    to_dir = os.path.abspath(to_dir)
+    try:
+        from urllib.request import urlopen
+    except ImportError:
+        from urllib2 import urlopen
+    tgz_name = "distribute-%s.tar.gz" % version
+    url = download_base + tgz_name
+    saveto = os.path.join(to_dir, tgz_name)
+    src = dst = None
+    if not os.path.exists(saveto):  # Avoid repeated downloads
+        try:
+            log.warn("Downloading %s", url)
+            src = urlopen(url)
+            # Read/write all in one block, so we don't create a corrupt file
+            # if the download is interrupted.
+            data = src.read()
+            dst = open(saveto, "wb")
+            dst.write(data)
+        finally:
+            if src:
+                src.close()
+            if dst:
+                dst.close()
+    return os.path.realpath(saveto)
+
+
+def _patch_file(path, content):
+    """Will backup the file then patch it"""
+    existing_content = open(path).read()
+    if existing_content == content:
+        # already patched
+        log.warn('Already patched.')
+        return False
+    log.warn('Patching...')
+    _rename_path(path)
+    f = open(path, 'w')
+    try:
+        f.write(content)
+    finally:
+        f.close()
+    return True
+
+
+def _same_content(path, content):
+    return open(path).read() == content
+
+def _no_sandbox(function):
+    def __no_sandbox(*args, **kw):
+        try:
+            from setuptools.sandbox import DirectorySandbox
+            def violation(*args):
+                pass
+            DirectorySandbox._old = DirectorySandbox._violation
+            DirectorySandbox._violation = violation
+            patched = True
+        except ImportError:
+            patched = False
+
+        try:
+            return function(*args, **kw)
+        finally:
+            if patched:
+                DirectorySandbox._violation = DirectorySandbox._old
+                del DirectorySandbox._old
+
+    return __no_sandbox
+
+@_no_sandbox
+def _rename_path(path):
+    new_name = path + '.OLD.%s' % time.time()
+    log.warn('Renaming %s into %s', path, new_name)
+    os.rename(path, new_name)
+    return new_name
+
+def _remove_flat_installation(placeholder):
+    if not os.path.isdir(placeholder):
+        log.warn('Unkown installation at %s', placeholder)
+        return False
+    found = False
+    for file in os.listdir(placeholder):
+        if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
+            found = True
+            break
+    if not found:
+        log.warn('Could not locate setuptools*.egg-info')
+        return
+
+    log.warn('Removing elements out of the way...')
+    pkg_info = os.path.join(placeholder, file)
+    if os.path.isdir(pkg_info):
+        patched = _patch_egg_dir(pkg_info)
+    else:
+        patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
+
+    if not patched:
+        log.warn('%s already patched.', pkg_info)
+        return False
+    # now let's move the files out of the way
+    for element in ('setuptools', 'pkg_resources.py', 'site.py'):
+        element = os.path.join(placeholder, element)
+        if os.path.exists(element):
+            _rename_path(element)
+        else:
+            log.warn('Could not find the %s element of the '
+                     'Setuptools distribution', element)
+    return True
+
+
+def _after_install(dist):
+    log.warn('After install bootstrap.')
+    placeholder = dist.get_command_obj('install').install_purelib
+    _create_fake_setuptools_pkg_info(placeholder)
+
+@_no_sandbox
+def _create_fake_setuptools_pkg_info(placeholder):
+    if not placeholder or not os.path.exists(placeholder):
+        log.warn('Could not find the install location')
+        return
+    pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
+    setuptools_file = 'setuptools-%s-py%s.egg-info' % \
+            (SETUPTOOLS_FAKED_VERSION, pyver)
+    pkg_info = os.path.join(placeholder, setuptools_file)
+    if os.path.exists(pkg_info):
+        log.warn('%s already exists', pkg_info)
+        return
+
+    log.warn('Creating %s', pkg_info)
+    f = open(pkg_info, 'w')
+    try:
+        f.write(SETUPTOOLS_PKG_INFO)
+    finally:
+        f.close()
+
+    pth_file = os.path.join(placeholder, 'setuptools.pth')
+    log.warn('Creating %s', pth_file)
+    f = open(pth_file, 'w')
+    try:
+        f.write(os.path.join(os.curdir, setuptools_file))
+    finally:
+        f.close()
+
+def _patch_egg_dir(path):
+    # let's check if it's already patched
+    pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
+    if os.path.exists(pkg_info):
+        if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
+            log.warn('%s already patched.', pkg_info)
+            return False
+    _rename_path(path)
+    os.mkdir(path)
+    os.mkdir(os.path.join(path, 'EGG-INFO'))
+    pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
+    f = open(pkg_info, 'w')
+    try:
+        f.write(SETUPTOOLS_PKG_INFO)
+    finally:
+        f.close()
+    return True
+
+
+def _before_install():
+    log.warn('Before install bootstrap.')
+    _fake_setuptools()
+
+
+def _under_prefix(location):
+    if 'install' not in sys.argv:
+        return True
+    args = sys.argv[sys.argv.index('install')+1:]
+    for index, arg in enumerate(args):
+        for option in ('--root', '--prefix'):
+            if arg.startswith('%s=' % option):
+                top_dir = arg.split('root=')[-1]
+                return location.startswith(top_dir)
+            elif arg == option:
+                if len(args) > index:
+                    top_dir = args[index+1]
+                    return location.startswith(top_dir)
+            elif option == '--user' and USER_SITE is not None:
+                return location.startswith(USER_SITE)
+    return True
+
+
+def _fake_setuptools():
+    log.warn('Scanning installed packages')
+    try:
+        import pkg_resources
+    except ImportError:
+        # we're cool
+        log.warn('Setuptools or Distribute does not seem to be installed.')
+        return
+    ws = pkg_resources.working_set
+    try:
+        setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools',
+                                  replacement=False))
+    except TypeError:
+        # old distribute API
+        setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools'))
+
+    if setuptools_dist is None:
+        log.warn('No setuptools distribution found')
+        return
+    # detecting if it was already faked
+    setuptools_location = setuptools_dist.location
+    log.warn('Setuptools installation detected at %s', setuptools_location)
+
+    # if --root or --preix was provided, and if
+    # setuptools is not located in them, we don't patch it
+    if not _under_prefix(setuptools_location):
+        log.warn('Not patching, --root or --prefix is installing Distribute'
+                 ' in another location')
+        return
+
+    # let's see if its an egg
+    if not setuptools_location.endswith('.egg'):
+        log.warn('Non-egg installation')
+        res = _remove_flat_installation(setuptools_location)
+        if not res:
+            return
+    else:
+        log.warn('Egg installation')
+        pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
+        if (os.path.exists(pkg_info) and
+            _same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
+            log.warn('Already patched.')
+            return
+        log.warn('Patching...')
+        # let's create a fake egg replacing setuptools one
+        res = _patch_egg_dir(setuptools_location)
+        if not res:
+            return
+    log.warn('Patched done.')
+    _relaunch()
+
+
+def _relaunch():
+    log.warn('Relaunching...')
+    # we have to relaunch the process
+    args = [sys.executable] + sys.argv
+    sys.exit(subprocess.call(args))
+
+
+def _extractall(self, path=".", members=None):
+    """Extract all members from the archive to the current working
+       directory and set owner, modification time and permissions on
+       directories afterwards. `path' specifies a different directory
+       to extract to. `members' is optional and must be a subset of the
+       list returned by getmembers().
+    """
+    import copy
+    import operator
+    from tarfile import ExtractError
+    directories = []
+
+    if members is None:
+        members = self
+
+    for tarinfo in members:
+        if tarinfo.isdir():
+            # Extract directories with a safe mode.
+            directories.append(tarinfo)
+            tarinfo = copy.copy(tarinfo)
+            tarinfo.mode = 448 # decimal for oct 0700
+        self.extract(tarinfo, path)
+
+    # Reverse sort directories.
+    if sys.version_info < (2, 4):
+        def sorter(dir1, dir2):
+            return cmp(dir1.name, dir2.name)
+        directories.sort(sorter)
+        directories.reverse()
+    else:
+        directories.sort(key=operator.attrgetter('name'), reverse=True)
+
+    # Set correct owner, mtime and filemode on directories.
+    for tarinfo in directories:
+        dirpath = os.path.join(path, tarinfo.name)
+        try:
+            self.chown(tarinfo, dirpath)
+            self.utime(tarinfo, dirpath)
+            self.chmod(tarinfo, dirpath)
+        except ExtractError:
+            e = sys.exc_info()[1]
+            if self.errorlevel > 1:
+                raise
+            else:
+                self._dbg(1, "tarfile: %s" % e)
+
+
+def main(argv, version=DEFAULT_VERSION):
+    """Install or upgrade setuptools and EasyInstall"""
+    tarball = download_setuptools()
+    _install(tarball)
+
+
+if __name__ == '__main__':
+    main(sys.argv[1:])

tests/testtemplate/mytemplates/__init__.py

Empty file added.

tests/testtemplate/mytemplates/main.py

+#!/usr/bin/env python
+# encoding: utf-8
+#
+# Copyright (c) 2010 Doug Hellmann.  All rights reserved.
+#
+"""virtualenvwrapper.project plugin for tests
+"""
+
+import logging
+import os
+
+log = logging.getLogger(__name__)
+
+def template(args):
+    """Creates a test file containing the args passed to us
+    """
+    log.info('Running test template with args %r', args)
+    project = args[0]
+    filename = 'TEST_FILE'
+    log.info('Writing to %s', filename)
+    output = open(filename, 'w')
+    try:
+        output.write('\n'.join(args))
+    finally:
+        output.close()
+    return

tests/testtemplate/setup.py

+#!/usr/bin/env python
+
+PROJECT = 'testtemplate'
+VERSION = '1.0'
+
+# Bootstrap installation of Distribute
+import distribute_setup
+distribute_setup.use_setuptools()
+
+from setuptools import setup, find_packages
+
+from distutils.util import convert_path
+from fnmatch import fnmatchcase
+
+import os
+import sys
+
+################################################################################
+# find_package_data is an Ian Bicking creation.
+
+# Provided as an attribute, so you can append to these instead
+# of replicating them:
+standard_exclude = ('*.py', '*.pyc', '*~', '.*', '*.bak', '*.swp*')
+standard_exclude_directories = ('.*', 'CVS', '_darcs', './build',
+                                './dist', 'EGG-INFO', '*.egg-info')
+
+def find_package_data(
+    where='.', package='',
+    exclude=standard_exclude,
+    exclude_directories=standard_exclude_directories,
+    only_in_packages=True,
+    show_ignored=False):
+    """
+    Return a dictionary suitable for use in ``package_data``
+    in a distutils ``setup.py`` file.
+
+    The dictionary looks like::
+
+        {'package': [files]}
+
+    Where ``files`` is a list of all the files in that package that
+    don't match anything in ``exclude``.
+
+    If ``only_in_packages`` is true, then top-level directories that
+    are not packages won't be included (but directories under packages
+    will).
+
+    Directories matching any pattern in ``exclude_directories`` will
+    be ignored; by default directories with leading ``.``, ``CVS``,
+    and ``_darcs`` will be ignored.
+
+    If ``show_ignored`` is true, then all the files that aren't
+    included in package data are shown on stderr (for debugging
+    purposes).
+
+    Note patterns use wildcards, or can be exact paths (including
+    leading ``./``), and all searching is case-insensitive.
+    
+    This function is by Ian Bicking.
+    """
+
+    out = {}
+    stack = [(convert_path(where), '', package, only_in_packages)]
+    while stack:
+        where, prefix, package, only_in_packages = stack.pop(0)
+        for name in os.listdir(where):
+            fn = os.path.join(where, name)
+            if os.path.isdir(fn):
+                bad_name = False
+                for pattern in exclude_directories:
+                    if (fnmatchcase(name, pattern)
+                        or fn.lower() == pattern.lower()):
+                        bad_name = True
+                        if show_ignored:
+                            print >> sys.stderr, (
+                                "Directory %s ignored by pattern %s"
+                                % (fn, pattern))
+                        break
+                if bad_name:
+                    continue
+                if os.path.isfile(os.path.join(fn, '__init__.py')):
+                    if not package:
+                        new_package = name
+                    else:
+                        new_package = package + '.' + name
+                    stack.append((fn, '', new_package, False))
+                else:
+                    stack.append((fn, prefix + name + '/', package, only_in_packages))
+            elif package or not only_in_packages:
+                # is a file
+                bad_name = False
+                for pattern in exclude:
+                    if (fnmatchcase(name, pattern)
+                        or fn.lower() == pattern.lower()):
+                        bad_name = True
+                        if show_ignored:
+                            print >> sys.stderr, (
+                                "File %s ignored by pattern %s"
+                                % (fn, pattern))
+                        break
+                if bad_name:
+                    continue
+                out.setdefault(package, []).append(prefix+name)
+    return out
+################################################################################
+
+setup(
+    name = PROJECT,
+    version = VERSION,
+    
+    description = 'template for testing mkproject',
+    
+    author = 'Doug Hellmann',
+    author_email = 'doug.hellmann@gmail.com',
+
+    url = 'http://www.doughellmann.com/projects/virtualenvwrapper/',
+
+    classifiers = [ 'Development Status :: 5 - Production/Stable',
+                    'License :: OSI Approved :: BSD License',
+                    'Programming Language :: Python',
+                    'Intended Audience :: Developers',
+                    'Environment :: Console',
+                    ],
+
+    platforms = ['Any'],
+
+    provides=['testtemplate',
+              ],
+    requires=['virtualenv',
+              'virtualenvwrapper (>=2.9)',
+              ],
+
+    packages = find_packages(),
+    include_package_data = True,
+    # Scan the input for package information
+    # to grab any data files (text, images, etc.) 
+    # associated with sub-packages.
+    package_data = find_package_data('mytemplates', 
+                                     package='mytemplates',
+                                     only_in_packages=False,
+                                     ),
+
+    entry_points = {
+        'virtualenvwrapper.project.template': [
+            'test = mytemplates.main:template',
+            ],
+        },
+
+    zip_safe=False,
+    )

virtualenvwrapper.sh

     VIRTUALENVWRAPPER_VIRTUALENV="virtualenv"
 fi
 
-virtualenvwrapper_derive_workon_home() {
+# Define script folder depending on the platorm (Win32/Unix)
+VIRTUALENVWRAPPER_ENV_BIN_DIR="bin"
+if [ "$OS" = "Windows_NT" ] && [