Doug Hellmann avatar Doug Hellmann committed 54f2258

implement initialize hooks

Comments (0)

Files changed (9)

 
     entry_points = {
         #'console_scripts': [ 'venvw_hook = virtualenvwrapper.hook_loader:main' ],
-        'virtualenvwrapper.pre_initialize_source': [
-            'user_scripts = virtualenvwrapper.user_scripts:pre_initialize_source',
-            'make_hooks = virtualenvwrapper.make_hooks:pre_initialize_source',
+        'virtualenvwrapper.initialize_source': [
+            'user_scripts = virtualenvwrapper.user_scripts:initialize_source',
             ],
+        'virtualenvwrapper.initialize': [
+            'make_hooks = virtualenvwrapper.make_hooks:initialize',
+            ]
         },
 
     zip_safe=False,
         assertTrue "Global $hook was not created" "[ -f $WORKON_HOME/$hook ]"
         assertTrue "Global $hook is not executable" "[ -x $WORKON_HOME/$hook ]"
     done
+    assertTrue "Log file was not created" "[ -f $WORKON_HOME/hook.log ]"
 }
 
 test_virtualenvwrapper_verify_workon_home() {

virtualenvwrapper.sh

     return 0
 }
 
-# Create a hook script
-#
-# Usage: virtualenvwrapper_make_hook filename comment
-#
-function virtualenvwrapper_make_hook () {
-    filename="$1"
-    comment="$2"
-    if [ ! -f "$filename" ]
-    then
-        #echo "Creating $filename"
-        cat - > "$filename" <<EOF
-#!/bin/sh
-# $comment
 
-EOF
-    fi
-    if [ ! -x "$filename" ]
-    then
-        chmod +x "$filename"
-    fi
+# Run a hook script in the current shell
+function virtualenvwrapper_source_hook () {
+    python -m virtualenvwrapper.hook_loader --source "${1}_source" >>$TMPDIR/$$.hook
+    source $TMPDIR/$$.hook
+    rm -f $TMPDIR/$$.hook
+}
+
+# Run a hook script in its own shell
+function virtualenvwrapper_run_hook () {
+    python -m virtualenvwrapper.hook_loader "$@"
 }
 
 # Set up virtualenvwrapper properly
 function virtualenvwrapper_initialize () {
     virtualenvwrapper_verify_workon_home -q || return 1
-    # mkvirtualenv
-    virtualenvwrapper_make_hook "$WORKON_HOME/premkvirtualenv" \
-        "This hook is run after a new virtualenv is created and before it is activated."
-    virtualenvwrapper_make_hook "$WORKON_HOME/postmkvirtualenv" \
-        "This hook is run after a new virtualenv is activated."
-    # rmvirtualenv
-    virtualenvwrapper_make_hook "$WORKON_HOME/prermvirtualenv" \
-        "This hook is run before a virtualenv is deleted."
-    virtualenvwrapper_make_hook "$WORKON_HOME/postrmvirtualenv" \
-        "This hook is run after a virtualenv is deleted."
-    # deactivate
-    virtualenvwrapper_make_hook "$WORKON_HOME/predeactivate" \
-        "This hook is run before every virtualenv is deactivated."
-    virtualenvwrapper_make_hook "$WORKON_HOME/postdeactivate" \
-        "This hook is run after every virtualenv is deactivated."
-    # activate
-    virtualenvwrapper_make_hook "$WORKON_HOME/preactivate" \
-        "This hook is run before every virtualenv is activated."
-    virtualenvwrapper_make_hook "$WORKON_HOME/postactivate" \
-        "This hook is run after every virtualenv is activated."
+    virtualenvwrapper_run_hook initialize
+    virtualenvwrapper_source_hook initialize
 }
 
 virtualenvwrapper_initialize
     return 0
 }
 
-# Run a hook script in the current shell
-function virtualenvwrapper_source_hook () {
-    scriptname="$1"
-    #echo "Looking for hook $scriptname"
-    if [ -f "$scriptname" ]
-    then
-        source "$scriptname"
-    fi
-}
-
-# Run a hook script in its own shell
-function virtualenvwrapper_run_hook () {
-    scriptname="$1"
-    shift
-    #echo "Looking for hook $scriptname"
-    if [ -x "$scriptname" ]
-    then
-        "$scriptname" "$@"
-    elif [ -e "$scriptname" ]
-    then
-        echo "Warning: Found \"$scriptname\" but it is not executable." 1>&2
-    fi
-}
-
 # Create a new environment, in the WORKON_HOME.
 #
 # Usage: mkvirtualenv [options] ENVNAME

virtualenvwrapper/hook_loader.py

 """Load hooks for virtualenvwrapper.
 """
 
+import logging
 import optparse
+import os
 
 import pkg_resources
 
 def main():
     parser = optparse.OptionParser(
-        usage='usage: %prog [options] <hook> [options]',
+        usage='usage: %prog [options] <hook> [<arguments>]',
         prog='virtualenvwrapper.hook_loader',
         description='Manage hooks for virtualenvwrapper',
         )
+    parser.add_option('-s', '--source',
+                      help='Print the shell commands to be run in the current shell',
+                      action='store_true',
+                      dest='sourcing',
+                      default=False,
+                      )
+    parser.add_option('-v', '--verbose',
+                      help='Show more information on the console',
+                      action='store_const',
+                      const=2,
+                      default=1,
+                      dest='verbose_level',
+                      )
+    parser.add_option('-q', '--quiet',
+                      help='Show less information on the console',
+                      action='store_const',
+                      const=0,
+                      dest='verbose_level',
+                      )
+    parser.disable_interspersed_args() # stop when we hit an option without an '-'
     options, args = parser.parse_args()
 
+    # Set up logging to a file and to the console
+    logging.basicConfig(
+        filename=os.path.expandvars(os.path.join('$WORKON_HOME', 'hook.log')),
+        level=logging.DEBUG,
+        format='%(asctime)s %(levelname)s %(name)s %(message)s',
+        )
+    console = logging.StreamHandler()
+    console_level = [ logging.WARNING,
+                      logging.INFO,
+                      logging.DEBUG,
+                      ][options.verbose_level]
+    console.setLevel(console_level)
+    formatter = logging.Formatter('%(message)s')
+    console.setFormatter(formatter)
+    logging.getLogger('').addHandler(console)
+
+    # Determine which hook we're running
+    if not args:
+        parser.error('Please specify the hook to run')
     hook = args[0]
-    print hook
 
     for ep in pkg_resources.iter_entry_points('virtualenvwrapper.%s' % hook):
         plugin = ep.load()
-        print plugin()
+        if options.sourcing:
+            # Show the shell commands so they can
+            # be run in the calling shell.
+            contents = (plugin(args[1:]) or '').strip()
+            if contents:
+                print contents
+                print
+        else:
+            # Just run the plugin ourselves
+            plugin(args[1:])
     return 0
 
 if __name__ == '__main__':

virtualenvwrapper/make_hooks.py

 """Plugin to create hooks during initialization phase.
 """
 
+import logging
+import os
+import stat
+
+log = logging.getLogger(__name__)
+
 import pkg_resources
 
-def pre_initialize_source():
-    return pkg_resources.resource_string(__name__, 'make_hooks_pre_initialize.sh')
+GLOBAL_HOOKS = [
+    # initialize
+    ("initialize",
+     "This hook is run during the startup phase when loading virtualenvwrapper.sh."),
 
+    # mkvirtualenv
+    ("premkvirtualenv",
+     "This hook is run after a new virtualenv is created and before it is activated."),
+    ("postmkvirtualenv",
+     "This hook is run after a new virtualenv is activated."),
+
+    # rmvirtualenv
+    ("prermvirtualenv",
+     "This hook is run before a virtualenv is deleted."),
+    ("postrmvirtualenv",
+     "This hook is run after a virtualenv is deleted."),
+
+    # deactivate
+    ("predeactivate",
+     "This hook is run before every virtualenv is deactivated."),
+    ("postdeactivate",
+     "This hook is run after every virtualenv is deactivated."),
+
+    # activate
+    ("preactivate",
+     "This hook is run before every virtualenv is activated."),
+    ("postactivate",
+     "This hook is run after every virtualenv is activated."),
+    
+    ]
+
+def make_hook(filename, comment, permissions):
+    """Create a hook script.
+    
+    :param filename: The name of the file to write.
+    :param comment: The comment to insert into the file.
+    """
+    filename = os.path.expanduser(os.path.expandvars(filename))
+    if not os.path.exists(filename):
+        log.info('Creating %s', filename)
+        with open(filename, 'wt') as f:
+            f.write("""#!/bin/sh
+# %s
+
+""" % comment)
+        os.chmod(filename, permissions)
+    return
+
+
+def initialize(args):
+    permissions = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH
+    for filename, comment in GLOBAL_HOOKS:
+        make_hook(os.path.join('$WORKON_HOME', filename), comment, permissions)
+    return
+
+

virtualenvwrapper/make_hooks_pre_initialize.sh

-#
-# Create the default hooks, if they do not exist on startup.
-#
-
-# Create a hook script
-#
-# Usage: virtualenvwrapper_make_hook filename comment
-#
-function virtualenvwrapper_make_hook () {
-    filename="$1"
-    comment="$2"
-    if [ ! -f "$filename" ]
-    then
-        #echo "Creating $filename"
-        cat - > "$filename" <<EOF
-#!/bin/sh
-# $comment
-
-EOF
-    fi
-    if [ ! -x "$filename" ]
-    then
-        chmod +x "$filename"
-    fi
-}
-
-# initialize
-virtualenvwrapper_make_hook "$WORKON_HOME/preinitialize" \
-    "This hook is run early in the startup phase when loading virtualenvwrapper.sh."
-virtualenvwrapper_make_hook "$WORKON_HOME/postinitialize" \
-    "This hook is run later in the startup phase when loading virtualenvwrapper.sh."
-# mkvirtualenv
-virtualenvwrapper_make_hook "$WORKON_HOME/premkvirtualenv" \
-    "This hook is run after a new virtualenv is created and before it is activated."
-virtualenvwrapper_make_hook "$WORKON_HOME/postmkvirtualenv" \
-    "This hook is run after a new virtualenv is activated."
-# rmvirtualenv
-virtualenvwrapper_make_hook "$WORKON_HOME/prermvirtualenv" \
-    "This hook is run before a virtualenv is deleted."
-virtualenvwrapper_make_hook "$WORKON_HOME/postrmvirtualenv" \
-    "This hook is run after a virtualenv is deleted."
-# deactivate
-virtualenvwrapper_make_hook "$WORKON_HOME/predeactivate" \
-    "This hook is run before every virtualenv is deactivated."
-virtualenvwrapper_make_hook "$WORKON_HOME/postdeactivate" \
-    "This hook is run after every virtualenv is deactivated."
-# activate
-virtualenvwrapper_make_hook "$WORKON_HOME/preactivate" \
-    "This hook is run before every virtualenv is activated."
-virtualenvwrapper_make_hook "$WORKON_HOME/postactivate" \
-    "This hook is run after every virtualenv is activated."

virtualenvwrapper/user_scripts.py

 """Plugin to handle hooks in user-defined scripts.
 """
 
+import logging
+
 import pkg_resources
 
-def pre_initialize_source():
-    return pkg_resources.resource_string(__name__, 'user_scripts_pre_initialize.sh')
+log = logging.getLogger(__name__)
+
+def initialize_source(args):
+    script_name = 'user_scripts_initialize.sh'
+    fname = pkg_resources.resource_filename(__name__, script_name)
+    log.debug('Looking for %s in %s', script_name, fname)
+    return pkg_resources.resource_string(__name__, script_name)

virtualenvwrapper/user_scripts_initialize.sh

+#
+# Run user-provided initialization scripts
+#
+global_script="$WORKON_HOME/initialize"
+[ -f "$global_script" ] && source "$global_script"

virtualenvwrapper/user_scripts_pre_initialize.sh

-#
-# Run user-provided initialization scripts
-#
-global_script="$WORKON_HOME/preinitialize"
-[ -f "$global_script" ] && source "$global_script"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.