This repository has been archived by the owner on May 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsetupbase.py
312 lines (251 loc) · 9.52 KB
/
setupbase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from os.path import join as pjoin
import functools
import pipes
from setuptools import Command
from setuptools.command.build_py import build_py
from setuptools.command.sdist import sdist
from setuptools.command.develop import develop
from setuptools.command.bdist_egg import bdist_egg
from distutils import log
from subprocess import check_call
import sys
try:
from wheel.bdist_wheel import bdist_wheel
except ImportError:
bdist_wheel = None
if sys.platform == 'win32':
from subprocess import list2cmdline
else:
def list2cmdline(cmd_list):
return ' '.join(map(pipes.quote, cmd_list))
__version__ = '0.1.0'
# ---------------------------------------------------------------------------
# Top Level Variables
# ---------------------------------------------------------------------------
here = os.path.abspath(os.path.dirname(sys.argv[0]))
is_repo = os.path.exists(pjoin(here, '.git'))
node_modules = pjoin(here, 'node_modules')
npm_path = ':'.join([
pjoin(here, 'node_modules', '.bin'),
os.environ.get('PATH', os.defpath),
])
if "--skip-npm" in sys.argv:
print("Skipping npm install as requested.")
skip_npm = True
sys.argv.remove("--skip-npm")
else:
skip_npm = False
# ---------------------------------------------------------------------------
# Public Functions
# ---------------------------------------------------------------------------
def get_data_files(top):
"""Get data files"""
data_files = []
ntrim = len(here + os.path.sep)
for (d, dirs, filenames) in os.walk(top):
data_files.append((
d[ntrim:],
[pjoin(d, f) for f in filenames]
))
return data_files
def find_packages(top):
"""
Find all of the packages.
"""
packages = []
for d, _, _ in os.walk(top):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(d.replace(os.path.sep, '.'))
def create_cmdclass(wrappers=None, data_dirs=None):
"""Create a command class with the given optional wrappers.
Parameters
----------
wrappers: list(str), optional
The cmdclass names to run before running other commands
data_dirs: list(str), optional.
The directories containing static data.
"""
egg = bdist_egg if 'bdist_egg' in sys.argv else bdist_egg_disabled
wrappers = wrappers or []
data_dirs = data_dirs or []
wrapper = functools.partial(wrap_command, wrappers, data_dirs)
cmdclass = dict(
build_py=wrapper(build_py, strict=is_repo),
sdist=wrapper(sdist, strict=True),
bdist_egg=egg,
develop=wrapper(develop, strict=True)
)
if bdist_wheel:
cmdclass['bdist_wheel'] = wrapper(bdist_wheel, strict=True)
return cmdclass
def run(cmd, *args, **kwargs):
"""Echo a command before running it. Defaults to repo as cwd"""
log.info('> ' + list2cmdline(cmd))
kwargs.setdefault('cwd', here)
kwargs.setdefault('shell', sys.platform == 'win32')
if not isinstance(cmd, list):
cmd = cmd.split()
return check_call(cmd, *args, **kwargs)
def is_stale(target, source):
"""Test whether the target file/directory is stale based on the source
file/directory.
"""
if not os.path.exists(target):
return True
return mtime(target) < mtime(source)
class BaseCommand(Command):
"""Empty command because Command needs subclasses to override too much"""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def get_inputs(self):
return []
def get_outputs(self):
return []
def combine_commands(*commands):
"""Return a Command that combines several commands."""
class CombinedCommand(Command):
def initialize_options(self):
self.commands = []
for C in commands:
self.commands.append(C(self.distribution))
for c in self.commands:
c.initialize_options()
def finalize_options(self):
for c in self.commands:
c.finalize_options()
def run(self):
for c in self.commands:
c.run()
return CombinedCommand
def mtime(path):
"""shorthand for mtime"""
return os.stat(path).st_mtime
def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='build'):
"""Return a Command for managing an npm installation.
Parameters
----------
path: str, optional
The base path of the node package. Defaults to the repo root.
build_dir: str, optional
The target build directory. If this and source_dir are given,
the JavaScript will only be build if necessary.
source_dir: str, optional
The source code directory.
build_cmd: str, optional
The npm command to build assets to the build_dir.
"""
class NPM(BaseCommand):
description = 'install package.json dependencies using npm'
def run(self):
if skip_npm:
log.info('Skipping npm-installation')
return
node_package = path or here
node_modules = pjoin(node_package, 'node_modules')
if not which("npm"):
log.error("`npm` unavailable. If you're running this command "
"using sudo, make sure `npm` is availble to sudo")
return
if is_stale(node_modules, pjoin(node_package, 'package.json')):
log.info('Installing build dependencies with npm. This may '
'take a while...')
run(['npm', 'install'], cwd=node_package)
if build_dir and source_dir:
should_build = is_stale(build_dir, source_dir)
else:
should_build = True
if should_build:
run(['npm', 'run', build_cmd], cwd=node_package)
return NPM
# `shutils.which` function copied verbatim from the Python-3.3 source.
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode) and
not os.path.isdir(fn))
# Short circuit. If we're given a full path which matches the mode
# and it exists, we're done here.
if _access_check(cmd, mode):
return cmd
path = (path or os.environ.get("PATH", os.defpath)).split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if os.curdir not in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())]
# If it does match, only test that one, otherwise we have to try
# others.
files = [cmd] if matches else [cmd + ext.lower() for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
dir = os.path.normcase(dir)
if dir not in seen:
seen.add(dir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
# ---------------------------------------------------------------------------
# Private Functions
# ---------------------------------------------------------------------------
def wrap_command(cmds, data_dirs, cls, strict=True):
"""Wrap a setup command
Parameters
----------
cmds: list(str)
The names of the other commands to run prior to the command.
strict: boolean, optional
Wether to raise errors when a pre-command fails.
"""
class WrappedCommand(cls):
def run(self):
if not getattr(self, 'uninstall', None):
try:
[self.run_command(cmd) for cmd in cmds]
except Exception:
if strict:
raise
else:
pass
result = cls.run(self)
data_files = []
for dname in data_dirs:
data_files.extend(get_data_files(dname))
# update data-files in case this created new files
self.distribution.data_files = data_files
return result
return WrappedCommand
class bdist_egg_disabled(bdist_egg):
"""Disabled version of bdist_egg
Prevents setup.py install performing setuptools' default easy_install,
which it should never ever do.
"""
def run(self):
sys.exit("Aborting implicit building of eggs. Use `pip install .` " +
" to install from source.")