##// END OF EJS Templates
Make user_setup a top-level function in iplib and add better tests....
Fernando Perez -
Show More
@@ -108,6 +108,197 b' def softspace(file, newvalue):'
108 return oldvalue
108 return oldvalue
109
109
110
110
111 def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
112 """Install or upgrade the user configuration directory.
113
114 Can be called when running for the first time or to upgrade the user's
115 .ipython/ directory.
116
117 Parameters
118 ----------
119 ipythondir : path
120 The directory to be used for installation/upgrade. In 'install' mode,
121 if this path already exists, the function exits immediately.
122
123 rc_suffix : str
124 Extension for the config files. On *nix platforms it is typically the
125 empty string, while Windows normally uses '.ini'.
126
127 mode : str, optional
128 Valid modes are 'install' and 'upgrade'.
129
130 interactive : bool, optional
131 If False, do not wait for user input on any errors. Normally after
132 printing its status information, this function waits for the user to
133 hit Return before proceeding. This is because the default use case is
134 when first installing the IPython configuration, so we want the user to
135 acknowledge the initial message, which contains some useful
136 information.
137 """
138
139 # For automatic use, deactivate all i/o
140 if interactive:
141 def wait():
142 try:
143 raw_input("Please press <RETURN> to start IPython.")
144 except EOFError:
145 print >> Term.cout
146 print '*'*70
147
148 def printf(s):
149 print s
150 else:
151 wait = lambda : None
152 printf = lambda s : None
153
154 # Install mode should be re-entrant: if the install dir already exists,
155 # bail out cleanly
156 if mode == 'install' and os.path.isdir(ipythondir):
157 return
158
159 cwd = os.getcwd() # remember where we started
160 glb = glob.glob
161
162 printf('*'*70)
163 if mode == 'install':
164 printf(
165 """Welcome to IPython. I will try to create a personal configuration directory
166 where you can customize many aspects of IPython's functionality in:\n""")
167 else:
168 printf('I am going to upgrade your configuration in:')
169
170 printf(ipythondir)
171
172 rcdirend = os.path.join('IPython','UserConfig')
173 cfg = lambda d: os.path.join(d,rcdirend)
174 try:
175 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
176 printf("Initializing from configuration: %s" % rcdir)
177 except IndexError:
178 warning = """
179 Installation error. IPython's directory was not found.
180
181 Check the following:
182
183 The ipython/IPython directory should be in a directory belonging to your
184 PYTHONPATH environment variable (that is, it should be in a directory
185 belonging to sys.path). You can copy it explicitly there or just link to it.
186
187 IPython will create a minimal default configuration for you.
188
189 """
190 warn(warning)
191 wait()
192
193 if sys.platform =='win32':
194 inif = 'ipythonrc.ini'
195 else:
196 inif = 'ipythonrc'
197 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
198 inif : '# intentionally left blank' }
199 os.makedirs(ipythondir, mode = 0777)
200 for f, cont in minimal_setup.items():
201 # In 2.5, this can be more cleanly done using 'with'
202 fobj = file(ipythondir + '/' + f,'w')
203 fobj.write(cont)
204 fobj.close()
205
206 return
207
208 if mode == 'install':
209 try:
210 shutil.copytree(rcdir,ipythondir)
211 os.chdir(ipythondir)
212 rc_files = glb("ipythonrc*")
213 for rc_file in rc_files:
214 os.rename(rc_file,rc_file+rc_suffix)
215 except:
216 warning = """
217
218 There was a problem with the installation:
219 %s
220 Try to correct it or contact the developers if you think it's a bug.
221 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
222 warn(warning)
223 wait()
224 return
225
226 elif mode == 'upgrade':
227 try:
228 os.chdir(ipythondir)
229 except:
230 printf("""
231 Can not upgrade: changing to directory %s failed. Details:
232 %s
233 """ % (ipythondir,sys.exc_info()[1]) )
234 wait()
235 return
236 else:
237 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
238 for new_full_path in sources:
239 new_filename = os.path.basename(new_full_path)
240 if new_filename.startswith('ipythonrc'):
241 new_filename = new_filename + rc_suffix
242 # The config directory should only contain files, skip any
243 # directories which may be there (like CVS)
244 if os.path.isdir(new_full_path):
245 continue
246 if os.path.exists(new_filename):
247 old_file = new_filename+'.old'
248 if os.path.exists(old_file):
249 os.remove(old_file)
250 os.rename(new_filename,old_file)
251 shutil.copy(new_full_path,new_filename)
252 else:
253 raise ValueError('unrecognized mode for install: %r' % mode)
254
255 # Fix line-endings to those native to each platform in the config
256 # directory.
257 try:
258 os.chdir(ipythondir)
259 except:
260 printf("""
261 Problem: changing to directory %s failed.
262 Details:
263 %s
264
265 Some configuration files may have incorrect line endings. This should not
266 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
267 wait()
268 else:
269 for fname in glb('ipythonrc*'):
270 try:
271 native_line_ends(fname,backup=0)
272 except IOError:
273 pass
274
275 if mode == 'install':
276 printf("""
277 Successful installation!
278
279 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
280 IPython manual (there are both HTML and PDF versions supplied with the
281 distribution) to make sure that your system environment is properly configured
282 to take advantage of IPython's features.
283
284 Important note: the configuration system has changed! The old system is
285 still in place, but its setting may be partly overridden by the settings in
286 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
287 if some of the new settings bother you.
288
289 """)
290 else:
291 printf("""
292 Successful upgrade!
293
294 All files in your directory:
295 %(ipythondir)s
296 which would have been overwritten by the upgrade were backed up with a .old
297 extension. If you had made particular customizations in those files you may
298 want to merge them back into the new files.""" % locals() )
299 wait()
300 os.chdir(cwd)
301
111 #****************************************************************************
302 #****************************************************************************
112 # Local use exceptions
303 # Local use exceptions
113 class SpaceInInput(exceptions.Exception): pass
304 class SpaceInInput(exceptions.Exception): pass
@@ -1114,161 +1305,11 b' class InteractiveShell(object,Magic):'
1114 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1305 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1115 """Install the user configuration directory.
1306 """Install the user configuration directory.
1116
1307
1117 Can be called when running for the first time or to upgrade the user's
1308 Note
1118 .ipython/ directory with the mode parameter. Valid modes are 'install'
1309 ----
1119 and 'upgrade'."""
1310 DEPRECATED: use the top-level user_setup() function instead.
1120
1311 """
1121 def wait():
1312 return user_setup(ipythondir,rc_suffix,mode)
1122 try:
1123 raw_input("Please press <RETURN> to start IPython.")
1124 except EOFError:
1125 print >> Term.cout
1126 print '*'*70
1127
1128 # Install mode should be re-entrant: if the install dir already exists,
1129 # bail out cleanly
1130 if mode == 'install' and os.path.isdir(ipythondir):
1131 return
1132
1133 cwd = os.getcwd() # remember where we started
1134 glb = glob.glob
1135 print '*'*70
1136 if mode == 'install':
1137 print \
1138 """Welcome to IPython. I will try to create a personal configuration directory
1139 where you can customize many aspects of IPython's functionality in:\n"""
1140 else:
1141 print 'I am going to upgrade your configuration in:'
1142
1143 print ipythondir
1144
1145 rcdirend = os.path.join('IPython','UserConfig')
1146 cfg = lambda d: os.path.join(d,rcdirend)
1147 try:
1148 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1149 print "Initializing from configuration",rcdir
1150 except IndexError:
1151 warning = """
1152 Installation error. IPython's directory was not found.
1153
1154 Check the following:
1155
1156 The ipython/IPython directory should be in a directory belonging to your
1157 PYTHONPATH environment variable (that is, it should be in a directory
1158 belonging to sys.path). You can copy it explicitly there or just link to it.
1159
1160 IPython will create a minimal default configuration for you.
1161
1162 """
1163 warn(warning)
1164 wait()
1165
1166 if sys.platform =='win32':
1167 inif = 'ipythonrc.ini'
1168 else:
1169 inif = 'ipythonrc'
1170 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
1171 inif : '# intentionally left blank' }
1172 os.makedirs(ipythondir, mode = 0777)
1173 for f, cont in minimal_setup.items():
1174 open(ipythondir + '/' + f,'w').write(cont)
1175
1176 return
1177
1178 if mode == 'install':
1179 try:
1180 shutil.copytree(rcdir,ipythondir)
1181 os.chdir(ipythondir)
1182 rc_files = glb("ipythonrc*")
1183 for rc_file in rc_files:
1184 os.rename(rc_file,rc_file+rc_suffix)
1185 except:
1186 warning = """
1187
1188 There was a problem with the installation:
1189 %s
1190 Try to correct it or contact the developers if you think it's a bug.
1191 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1192 warn(warning)
1193 wait()
1194 return
1195
1196 elif mode == 'upgrade':
1197 try:
1198 os.chdir(ipythondir)
1199 except:
1200 print """
1201 Can not upgrade: changing to directory %s failed. Details:
1202 %s
1203 """ % (ipythondir,sys.exc_info()[1])
1204 wait()
1205 return
1206 else:
1207 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1208 for new_full_path in sources:
1209 new_filename = os.path.basename(new_full_path)
1210 if new_filename.startswith('ipythonrc'):
1211 new_filename = new_filename + rc_suffix
1212 # The config directory should only contain files, skip any
1213 # directories which may be there (like CVS)
1214 if os.path.isdir(new_full_path):
1215 continue
1216 if os.path.exists(new_filename):
1217 old_file = new_filename+'.old'
1218 if os.path.exists(old_file):
1219 os.remove(old_file)
1220 os.rename(new_filename,old_file)
1221 shutil.copy(new_full_path,new_filename)
1222 else:
1223 raise ValueError,'unrecognized mode for install:',`mode`
1224
1225 # Fix line-endings to those native to each platform in the config
1226 # directory.
1227 try:
1228 os.chdir(ipythondir)
1229 except:
1230 print """
1231 Problem: changing to directory %s failed.
1232 Details:
1233 %s
1234
1235 Some configuration files may have incorrect line endings. This should not
1236 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1237 wait()
1238 else:
1239 for fname in glb('ipythonrc*'):
1240 try:
1241 native_line_ends(fname,backup=0)
1242 except IOError:
1243 pass
1244
1245 if mode == 'install':
1246 print """
1247 Successful installation!
1248
1249 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1250 IPython manual (there are both HTML and PDF versions supplied with the
1251 distribution) to make sure that your system environment is properly configured
1252 to take advantage of IPython's features.
1253
1254 Important note: the configuration system has changed! The old system is
1255 still in place, but its setting may be partly overridden by the settings in
1256 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1257 if some of the new settings bother you.
1258
1259 """
1260 else:
1261 print """
1262 Successful upgrade!
1263
1264 All files in your directory:
1265 %(ipythondir)s
1266 which would have been overwritten by the upgrade were backed up with a .old
1267 extension. If you had made particular customizations in those files you may
1268 want to merge them back into the new files.""" % locals()
1269 wait()
1270 os.chdir(cwd)
1271 # end user_setup()
1272
1313
1273 def atexit_operations(self):
1314 def atexit_operations(self):
1274 """This will be executed at the time of exit.
1315 """This will be executed at the time of exit.
@@ -1,12 +1,39 b''
1 """Tests for the key iplib module, where the main ipython class is defined.
1 """Tests for the key iplib module, where the main ipython class is defined.
2 """
2 """
3 #-----------------------------------------------------------------------------
4 # Module imports
5 #-----------------------------------------------------------------------------
3
6
7 # stdlib
8 import os
9 import shutil
10 import tempfile
11
12 # third party
4 import nose.tools as nt
13 import nose.tools as nt
5
14
6 # Useful global ipapi object and main IPython one
15 # our own packages
7 ip = _ip
16 from IPython import iplib
8 IP = ip.IP
17
18 #-----------------------------------------------------------------------------
19 # Globals
20 #-----------------------------------------------------------------------------
21
22 # Useful global ipapi object and main IPython one. Unfortunately we have a
23 # long precedent of carrying the 'ipapi' global object which is injected into
24 # the system namespace as _ip, but that keeps a pointer to the actual IPython
25 # InteractiveShell instance, which is named IP. Since in testing we do need
26 # access to the real thing (we want to probe beyond what ipapi exposes), make
27 # here a global reference to each. In general, things that are exposed by the
28 # ipapi instance should be read from there, but we also will often need to use
29 # the actual IPython one.
9
30
31 ip = _ip # This is the ipapi instance
32 IP = ip.IP # This is the actual IPython shell 'raw' object.
33
34 #-----------------------------------------------------------------------------
35 # Test functions
36 #-----------------------------------------------------------------------------
10
37
11 def test_reset():
38 def test_reset():
12 """reset must clear most namespaces."""
39 """reset must clear most namespaces."""
@@ -20,8 +47,22 b' def test_reset():'
20 nt.assert_equals(len(ns),0)
47 nt.assert_equals(len(ns),0)
21
48
22
49
50 # make sure that user_setup can be run re-entrantly in 'install' mode.
23 def test_user_setup():
51 def test_user_setup():
24 """make sure that user_setup can be run re-entrantly in 'install' mode.
52 # use a lambda to pass kwargs to the generator
25 """
53 user_setup = lambda a,k: iplib.user_setup(*a,**k)
26 # This should basically run without errors or output.
54 kw = dict(mode='install',interactive=False)
27 IP.user_setup(ip.options.ipythondir,'','install')
55
56 # Call the user setup and verify that the directory exists
57 yield user_setup, (ip.options.ipythondir,''),kw
58 yield os.path.isdir,ip.options.ipythondir
59
60 # Now repeat the operation with a non-existent directory. Check both that
61 # the call succeeds and that the directory is created.
62 tmpdir = tempfile.mktemp(prefix='ipython-test-')
63 try:
64 yield user_setup, (tmpdir,''),kw
65 yield os.path.isdir,tmpdir
66 finally:
67 # In this case, clean up the temp dir once done
68 shutil.rmtree(tmpdir)
General Comments 0
You need to be logged in to leave comments. Login now