##// END OF EJS Templates
Revert "use testpath.tempdir for utils.tempdir"
Min RK -
Show More
@@ -1,5 +1,145 b''
1 from warnings import warn
1 """TemporaryDirectory class, copied from Python 3.2.
2 2
3 warn("IPython.utils.tempdir is deprecated. Use testpath.tempdir")
3 This is copied from the stdlib and will be standard in Python 3.2 and onwards.
4 """
5 from __future__ import print_function
6
7 import os as _os
8 import warnings as _warnings
9 import sys as _sys
10
11 # This code should only be used in Python versions < 3.2, since after that we
12 # can rely on the stdlib itself.
13 try:
14 from tempfile import TemporaryDirectory
15
16 except ImportError:
17 from tempfile import mkdtemp, template
18
19 class TemporaryDirectory(object):
20 """Create and return a temporary directory. This has the same
21 behavior as mkdtemp but can be used as a context manager. For
22 example:
23
24 with TemporaryDirectory() as tmpdir:
25 ...
26
27 Upon exiting the context, the directory and everthing contained
28 in it are removed.
29 """
30
31 def __init__(self, suffix="", prefix=template, dir=None):
32 self.name = mkdtemp(suffix, prefix, dir)
33 self._closed = False
34
35 def __enter__(self):
36 return self.name
37
38 def cleanup(self, _warn=False):
39 if self.name and not self._closed:
40 try:
41 self._rmtree(self.name)
42 except (TypeError, AttributeError) as ex:
43 # Issue #10188: Emit a warning on stderr
44 # if the directory could not be cleaned
45 # up due to missing globals
46 if "None" not in str(ex):
47 raise
48 print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
49 file=_sys.stderr)
50 return
51 self._closed = True
52 if _warn:
53 self._warn("Implicitly cleaning up {!r}".format(self),
54 Warning)
55
56 def __exit__(self, exc, value, tb):
57 self.cleanup()
58
59 def __del__(self):
60 # Issue a ResourceWarning if implicit cleanup needed
61 self.cleanup(_warn=True)
62
63
64 # XXX (ncoghlan): The following code attempts to make
65 # this class tolerant of the module nulling out process
66 # that happens during CPython interpreter shutdown
67 # Alas, it doesn't actually manage it. See issue #10188
68 _listdir = staticmethod(_os.listdir)
69 _path_join = staticmethod(_os.path.join)
70 _isdir = staticmethod(_os.path.isdir)
71 _remove = staticmethod(_os.remove)
72 _rmdir = staticmethod(_os.rmdir)
73 _os_error = _os.error
74 _warn = _warnings.warn
75
76 def _rmtree(self, path):
77 # Essentially a stripped down version of shutil.rmtree. We can't
78 # use globals because they may be None'ed out at shutdown.
79 for name in self._listdir(path):
80 fullname = self._path_join(path, name)
81 try:
82 isdir = self._isdir(fullname)
83 except self._os_error:
84 isdir = False
85 if isdir:
86 self._rmtree(fullname)
87 else:
88 try:
89 self._remove(fullname)
90 except self._os_error:
91 pass
92 try:
93 self._rmdir(path)
94 except self._os_error:
95 pass
96
97
98 class NamedFileInTemporaryDirectory(object):
99
100 def __init__(self, filename, mode='w+b', bufsize=-1, **kwds):
101 """
102 Open a file named `filename` in a temporary directory.
103
104 This context manager is preferred over `NamedTemporaryFile` in
105 stdlib `tempfile` when one needs to reopen the file.
106
107 Arguments `mode` and `bufsize` are passed to `open`.
108 Rest of the arguments are passed to `TemporaryDirectory`.
109
110 """
111 self._tmpdir = TemporaryDirectory(**kwds)
112 path = _os.path.join(self._tmpdir.name, filename)
113 self.file = open(path, mode, bufsize)
114
115 def cleanup(self):
116 self.file.close()
117 self._tmpdir.cleanup()
118
119 __del__ = cleanup
120
121 def __enter__(self):
122 return self.file
123
124 def __exit__(self, type, value, traceback):
125 self.cleanup()
126
127
128 class TemporaryWorkingDirectory(TemporaryDirectory):
129 """
130 Creates a temporary directory and sets the cwd to that directory.
131 Automatically reverts to previous cwd upon cleanup.
132 Usage example:
133
134 with TemporaryWorkingDirectory() as tmpdir:
135 ...
136 """
137 def __enter__(self):
138 self.old_wd = _os.getcwd()
139 _os.chdir(self.name)
140 return super(TemporaryWorkingDirectory, self).__enter__()
141
142 def __exit__(self, exc, value, tb):
143 _os.chdir(self.old_wd)
144 return super(TemporaryWorkingDirectory, self).__exit__(exc, value, tb)
4 145
5 from testpath.tempdir import *
@@ -1,360 +1,360 b''
1 1 #!/usr/bin/env python
2 2 # -*- coding: utf-8 -*-
3 3 """Setup script for IPython.
4 4
5 5 Under Posix environments it works like a typical setup.py script.
6 6 Under Windows, the command sdist is not supported, since IPython
7 7 requires utilities which are not available under Windows."""
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (c) 2008-2011, IPython Development Team.
11 11 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
12 12 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
13 13 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
14 14 #
15 15 # Distributed under the terms of the Modified BSD License.
16 16 #
17 17 # The full license is in the file COPYING.rst, distributed with this software.
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Minimal Python version sanity check
22 22 #-----------------------------------------------------------------------------
23 23 from __future__ import print_function
24 24
25 25 import sys
26 26
27 27 # This check is also made in IPython/__init__, don't forget to update both when
28 28 # changing Python version requirements.
29 29 v = sys.version_info
30 30 if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
31 31 error = "ERROR: IPython requires Python version 2.7 or 3.3 or above."
32 32 print(error, file=sys.stderr)
33 33 sys.exit(1)
34 34
35 35 PY3 = (sys.version_info[0] >= 3)
36 36
37 37 # At least we're on the python version we need, move on.
38 38
39 39 #-------------------------------------------------------------------------------
40 40 # Imports
41 41 #-------------------------------------------------------------------------------
42 42
43 43 # Stdlib imports
44 44 import os
45 45 import shutil
46 46
47 47 from glob import glob
48 48
49 49 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
50 50 # update it when the contents of directories change.
51 51 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
52 52
53 53 from distutils.core import setup
54 54
55 55 # Our own imports
56 56 from setupbase import target_update
57 57
58 58 from setupbase import (
59 59 setup_args,
60 60 find_packages,
61 61 find_package_data,
62 62 check_package_data_first,
63 63 find_entry_points,
64 64 build_scripts_entrypt,
65 65 find_data_files,
66 66 check_for_readline,
67 67 git_prebuild,
68 68 check_submodule_status,
69 69 update_submodules,
70 70 require_submodules,
71 71 UpdateSubmodules,
72 72 get_bdist_wheel,
73 73 CompileCSS,
74 74 JavascriptVersion,
75 75 css_js_prerelease,
76 76 install_symlinked,
77 77 install_lib_symlink,
78 78 install_scripts_for_symlink,
79 79 unsymlink,
80 80 )
81 81
82 82 isfile = os.path.isfile
83 83 pjoin = os.path.join
84 84
85 85 #-------------------------------------------------------------------------------
86 86 # Handle OS specific things
87 87 #-------------------------------------------------------------------------------
88 88
89 89 if os.name in ('nt','dos'):
90 90 os_name = 'windows'
91 91 else:
92 92 os_name = os.name
93 93
94 94 # Under Windows, 'sdist' has not been supported. Now that the docs build with
95 95 # Sphinx it might work, but let's not turn it on until someone confirms that it
96 96 # actually works.
97 97 if os_name == 'windows' and 'sdist' in sys.argv:
98 98 print('The sdist command is not available under Windows. Exiting.')
99 99 sys.exit(1)
100 100
101 101 #-------------------------------------------------------------------------------
102 102 # Make sure we aren't trying to run without submodules
103 103 #-------------------------------------------------------------------------------
104 104 here = os.path.abspath(os.path.dirname(__file__))
105 105
106 106 def require_clean_submodules():
107 107 """Check on git submodules before distutils can do anything
108 108
109 109 Since distutils cannot be trusted to update the tree
110 110 after everything has been set in motion,
111 111 this is not a distutils command.
112 112 """
113 113 # PACKAGERS: Add a return here to skip checks for git submodules
114 114
115 115 # don't do anything if nothing is actually supposed to happen
116 116 for do_nothing in ('-h', '--help', '--help-commands', 'clean', 'submodule'):
117 117 if do_nothing in sys.argv:
118 118 return
119 119
120 120 status = check_submodule_status(here)
121 121
122 122 if status == "missing":
123 123 print("checking out submodules for the first time")
124 124 update_submodules(here)
125 125 elif status == "unclean":
126 126 print('\n'.join([
127 127 "Cannot build / install IPython with unclean submodules",
128 128 "Please update submodules with",
129 129 " python setup.py submodule",
130 130 "or",
131 131 " git submodule update",
132 132 "or commit any submodule changes you have made."
133 133 ]))
134 134 sys.exit(1)
135 135
136 136 require_clean_submodules()
137 137
138 138 #-------------------------------------------------------------------------------
139 139 # Things related to the IPython documentation
140 140 #-------------------------------------------------------------------------------
141 141
142 142 # update the manuals when building a source dist
143 143 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
144 144
145 145 # List of things to be updated. Each entry is a triplet of args for
146 146 # target_update()
147 147 to_update = [
148 148 # FIXME - Disabled for now: we need to redo an automatic way
149 149 # of generating the magic info inside the rst.
150 150 #('docs/magic.tex',
151 151 #['IPython/Magic.py'],
152 152 #"cd doc && ./update_magic.sh" ),
153 153
154 154 ('docs/man/ipcluster.1.gz',
155 155 ['docs/man/ipcluster.1'],
156 156 'cd docs/man && gzip -9c ipcluster.1 > ipcluster.1.gz'),
157 157
158 158 ('docs/man/ipcontroller.1.gz',
159 159 ['docs/man/ipcontroller.1'],
160 160 'cd docs/man && gzip -9c ipcontroller.1 > ipcontroller.1.gz'),
161 161
162 162 ('docs/man/ipengine.1.gz',
163 163 ['docs/man/ipengine.1'],
164 164 'cd docs/man && gzip -9c ipengine.1 > ipengine.1.gz'),
165 165
166 166 ('docs/man/ipython.1.gz',
167 167 ['docs/man/ipython.1'],
168 168 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'),
169 169
170 170 ]
171 171
172 172
173 173 [ target_update(*t) for t in to_update ]
174 174
175 175 #---------------------------------------------------------------------------
176 176 # Find all the packages, package data, and data_files
177 177 #---------------------------------------------------------------------------
178 178
179 179 packages = find_packages()
180 180 package_data = find_package_data()
181 181
182 182 data_files = find_data_files()
183 183
184 184 setup_args['packages'] = packages
185 185 setup_args['package_data'] = package_data
186 186 setup_args['data_files'] = data_files
187 187
188 188 #---------------------------------------------------------------------------
189 189 # custom distutils commands
190 190 #---------------------------------------------------------------------------
191 191 # imports here, so they are after setuptools import if there was one
192 192 from distutils.command.sdist import sdist
193 193 from distutils.command.upload import upload
194 194
195 195 class UploadWindowsInstallers(upload):
196 196
197 197 description = "Upload Windows installers to PyPI (only used from tools/release_windows.py)"
198 198 user_options = upload.user_options + [
199 199 ('files=', 'f', 'exe file (or glob) to upload')
200 200 ]
201 201 def initialize_options(self):
202 202 upload.initialize_options(self)
203 203 meta = self.distribution.metadata
204 204 base = '{name}-{version}'.format(
205 205 name=meta.get_name(),
206 206 version=meta.get_version()
207 207 )
208 208 self.files = os.path.join('dist', '%s.*.exe' % base)
209 209
210 210 def run(self):
211 211 for dist_file in glob(self.files):
212 212 self.upload_file('bdist_wininst', 'any', dist_file)
213 213
214 214 setup_args['cmdclass'] = {
215 215 'build_py': css_js_prerelease(
216 216 check_package_data_first(git_prebuild('IPython'))),
217 217 'sdist' : css_js_prerelease(git_prebuild('IPython', sdist)),
218 218 'upload_wininst' : UploadWindowsInstallers,
219 219 'submodule' : UpdateSubmodules,
220 220 'css' : CompileCSS,
221 221 'symlink': install_symlinked,
222 222 'install_lib_symlink': install_lib_symlink,
223 223 'install_scripts_sym': install_scripts_for_symlink,
224 224 'unsymlink': unsymlink,
225 225 'jsversion' : JavascriptVersion,
226 226 }
227 227
228 228 ### Temporarily disable install while it's broken during the big split
229 229 from textwrap import dedent
230 230 from distutils.command.install import install
231 231
232 232 class DisabledInstall(install):
233 233 def run(self):
234 234 msg = dedent("""
235 235 While we are in the midst of The Big Split,
236 236 IPython cannot be installed from master.
237 237 You can use `pip install -e .` for an editable install,
238 238 which still works.
239 239 """)
240 240 print(msg, file=sys.stderr)
241 241 raise SystemExit(1)
242 242
243 243 setup_args['cmdclass']['install'] = DisabledInstall
244 244
245 245
246 246 #---------------------------------------------------------------------------
247 247 # Handle scripts, dependencies, and setuptools specific things
248 248 #---------------------------------------------------------------------------
249 249
250 250 # For some commands, use setuptools. Note that we do NOT list install here!
251 251 # If you want a setuptools-enhanced install, just run 'setupegg.py install'
252 252 needs_setuptools = set(('develop', 'release', 'bdist_egg', 'bdist_rpm',
253 253 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel',
254 254 'egg_info', 'easy_install', 'upload', 'install_egg_info',
255 255 ))
256 256
257 257 if len(needs_setuptools.intersection(sys.argv)) > 0:
258 258 import setuptools
259 259
260 260 # This dict is used for passing extra arguments that are setuptools
261 261 # specific to setup
262 262 setuptools_extra_args = {}
263 263
264 264 # setuptools requirements
265 265
266 266 pyzmq = 'pyzmq>=13'
267 267
268 268 extras_require = dict(
269 269 parallel = [pyzmq],
270 270 qtconsole = [pyzmq, 'pygments'],
271 271 doc = ['Sphinx>=1.1', 'numpydoc'],
272 test = ['nose>=0.10.1', 'requests', 'testpath'],
272 test = ['nose>=0.10.1', 'requests'],
273 273 terminal = [],
274 274 nbformat = ['jsonschema>=2.0'],
275 275 notebook = ['tornado>=4.0', pyzmq, 'jinja2', 'pygments', 'mistune>=0.5'],
276 276 nbconvert = ['pygments', 'jinja2', 'mistune>=0.3.1']
277 277 )
278 278
279 279 if not sys.platform.startswith('win'):
280 280 extras_require['notebook'].append('terminado>=0.3.3')
281 281
282 282 if sys.version_info < (3, 3):
283 283 extras_require['test'].append('mock')
284 284
285 285 extras_require['notebook'].extend(extras_require['nbformat'])
286 286 extras_require['nbconvert'].extend(extras_require['nbformat'])
287 287
288 288 install_requires = [
289 289 'decorator',
290 290 'pickleshare',
291 291 'simplegeneric>0.8',
292 292 ]
293 293
294 294 # add platform-specific dependencies
295 295 if sys.platform == 'darwin':
296 296 install_requires.append('appnope')
297 297 if 'bdist_wheel' in sys.argv[1:] or not check_for_readline():
298 298 install_requires.append('gnureadline')
299 299
300 300 if sys.platform.startswith('win'):
301 301 extras_require['terminal'].append('pyreadline>=2.0')
302 302 else:
303 303 install_requires.append('pexpect')
304 304
305 305 everything = set()
306 306 for deps in extras_require.values():
307 307 everything.update(deps)
308 308 extras_require['all'] = everything
309 309
310 310 if 'setuptools' in sys.modules:
311 311 # setup.py develop should check for submodules
312 312 from setuptools.command.develop import develop
313 313 setup_args['cmdclass']['develop'] = require_submodules(develop)
314 314 setup_args['cmdclass']['bdist_wheel'] = css_js_prerelease(get_bdist_wheel())
315 315
316 316 setuptools_extra_args['zip_safe'] = False
317 317 setuptools_extra_args['entry_points'] = {
318 318 'console_scripts': find_entry_points(),
319 319 'pygments.lexers': [
320 320 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer',
321 321 'ipython = IPython.lib.lexers:IPythonLexer',
322 322 'ipython3 = IPython.lib.lexers:IPython3Lexer',
323 323 ],
324 324 }
325 325 setup_args['extras_require'] = extras_require
326 326 requires = setup_args['install_requires'] = install_requires
327 327
328 328 # Script to be run by the windows binary installer after the default setup
329 329 # routine, to add shortcuts and similar windows-only things. Windows
330 330 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
331 331 # doesn't find them.
332 332 if 'bdist_wininst' in sys.argv:
333 333 if len(sys.argv) > 2 and \
334 334 ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
335 335 print("ERROR: bdist_wininst must be run alone. Exiting.", file=sys.stderr)
336 336 sys.exit(1)
337 337 setup_args['data_files'].append(
338 338 ['Scripts', ('scripts/ipython.ico', 'scripts/ipython_nb.ico')])
339 339 setup_args['scripts'] = [pjoin('scripts','ipython_win_post_install.py')]
340 340 setup_args['options'] = {"bdist_wininst":
341 341 {"install_script":
342 342 "ipython_win_post_install.py"}}
343 343
344 344 else:
345 345 # scripts has to be a non-empty list, or install_scripts isn't called
346 346 setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()]
347 347
348 348 setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt
349 349
350 350 #---------------------------------------------------------------------------
351 351 # Do the actual setup now
352 352 #---------------------------------------------------------------------------
353 353
354 354 setup_args.update(setuptools_extra_args)
355 355
356 356 def main():
357 357 setup(**setup_args)
358 358
359 359 if __name__ == '__main__':
360 360 main()
General Comments 0
You need to be logged in to leave comments. Login now