8
8
9
9
import logging
10
10
import os
11
+ import stat
11
12
import subprocess
12
13
13
14
import pkg_resources
@@ -41,9 +42,83 @@ def run_global(script_name, *args):
41
42
return
42
43
43
44
45
+ PERMISSIONS = stat .S_IRWXU | stat .S_IRWXG | stat .S_IROTH | stat .S_IXOTH
46
+
47
+
48
+ GLOBAL_HOOKS = [
49
+ # initialize
50
+ ("initialize" ,
51
+ "This hook is run during the startup phase when loading virtualenvwrapper.sh." ),
52
+
53
+ # mkvirtualenv
54
+ ("premkvirtualenv" ,
55
+ "This hook is run after a new virtualenv is created and before it is activated." ),
56
+ ("postmkvirtualenv" ,
57
+ "This hook is run after a new virtualenv is activated." ),
58
+
59
+ # rmvirtualenv
60
+ ("prermvirtualenv" ,
61
+ "This hook is run before a virtualenv is deleted." ),
62
+ ("postrmvirtualenv" ,
63
+ "This hook is run after a virtualenv is deleted." ),
64
+
65
+ # deactivate
66
+ ("predeactivate" ,
67
+ "This hook is run before every virtualenv is deactivated." ),
68
+ ("postdeactivate" ,
69
+ "This hook is run after every virtualenv is deactivated." ),
70
+
71
+ # activate
72
+ ("preactivate" ,
73
+ "This hook is run before every virtualenv is activated." ),
74
+ ("postactivate" ,
75
+ "This hook is run after every virtualenv is activated." ),
76
+ ]
77
+
78
+
79
+ LOCAL_HOOKS = [
80
+ # deactivate
81
+ ("predeactivate" ,
82
+ "This hook is run before this virtualenv is deactivated." ),
83
+ ("postdeactivate" ,
84
+ "This hook is run after this virtualenv is deactivated." ),
85
+
86
+ # activate
87
+ ("preactivate" ,
88
+ "This hook is run before this virtualenv is activated." ),
89
+ ("postactivate" ,
90
+ "This hook is run after this virtualenv is activated." ),
91
+ ]
92
+
93
+
94
+ def make_hook (filename , comment ):
95
+ """Create a hook script.
96
+
97
+ :param filename: The name of the file to write.
98
+ :param comment: The comment to insert into the file.
99
+ """
100
+ filename = os .path .expanduser (os .path .expandvars (filename ))
101
+ if not os .path .exists (filename ):
102
+ log .info ('Creating %s' , filename )
103
+ with open (filename , 'wt' ) as f :
104
+ f .write ("""#!%(shell)s
105
+ # %(comment)s
106
+
107
+ """ % {'comment' :comment , 'shell' :os .environ .get ('SHELL' , '/bin/sh' )})
108
+ os .chmod (filename , PERMISSIONS )
109
+ return
110
+
111
+
44
112
45
113
# HOOKS
46
114
115
+
116
+ def initialize (args ):
117
+ for filename , comment in GLOBAL_HOOKS :
118
+ make_hook (os .path .join ('$WORKON_HOME' , filename ), comment )
119
+ return
120
+
121
+
47
122
def initialize_source (args ):
48
123
return """
49
124
#
@@ -54,6 +129,9 @@ def initialize_source(args):
54
129
55
130
def pre_mkvirtualenv (args ):
56
131
log .debug ('pre_mkvirtualenv %s' , str (args ))
132
+ envname = args [0 ]
133
+ for filename , comment in LOCAL_HOOKS :
134
+ make_hook (os .path .join ('$WORKON_HOME' , envname , 'bin' , filename ), comment )
57
135
run_global ('premkvirtualenv' , * args )
58
136
return
59
137
0 commit comments