forked from ekalinin/nodeenv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodeenv.py
1519 lines (1269 loc) · 44.7 KB
/
nodeenv.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
nodeenv
~~~~~~~
Node.js virtual environment
:copyright: (c) 2014 by Eugene Kalinin
:license: BSD, see LICENSE for more details.
"""
import contextlib
import io
import json
import sys
import os
import re
import ssl
import stat
import logging
import operator
import argparse
import subprocess
import tarfile
import pipes
import platform
import zipfile
import shutil
import sysconfig
import glob
try: # pragma: no cover (py2 only)
from ConfigParser import SafeConfigParser as ConfigParser
# noinspection PyCompatibility
import urllib2
iteritems = operator.methodcaller('iteritems')
import httplib
IncompleteRead = httplib.IncompleteRead
except ImportError: # pragma: no cover (py3 only)
from configparser import ConfigParser
# noinspection PyUnresolvedReferences
import urllib.request as urllib2
iteritems = operator.methodcaller('items')
import http
IncompleteRead = http.client.IncompleteRead
from pkg_resources import parse_version
nodeenv_version = '1.7.0'
join = os.path.join
abspath = os.path.abspath
src_base_url = None
is_PY3 = sys.version_info[0] >= 3
is_WIN = platform.system() == 'Windows'
is_CYGWIN = platform.system().startswith(('CYGWIN', 'MSYS'))
ignore_ssl_certs = False
# ---------------------------------------------------------
# Utils
# https://github.com/jhermann/waif/blob/master/python/to_uft8.py
def to_utf8(text):
"""Convert given text to UTF-8 encoding (as far as possible)."""
if not text or is_PY3:
return text
try: # unicode or pure ascii
return text.encode("utf8")
except UnicodeDecodeError:
try: # successful UTF-8 decode means it's pretty sure UTF-8
text.decode("utf8")
return text
except UnicodeDecodeError:
try: # get desperate; and yes, this has a western hemisphere bias
return text.decode("cp1252").encode("utf8")
except UnicodeDecodeError:
pass
return text # return unchanged, hope for the best
class Config(object):
"""
Configuration namespace.
"""
# Defaults
node = 'latest'
npm = 'latest'
with_npm = False
jobs = '2'
without_ssl = False
debug = False
profile = False
make = 'make'
prebuilt = True
ignore_ssl_certs = False
mirror = None
@classmethod
def _load(cls, configfiles, verbose=False):
"""
Load configuration from the given files in reverse order,
if they exist and have a [nodeenv] section.
Additionally, load version from .node-version if file exists.
"""
for configfile in reversed(configfiles):
configfile = os.path.expanduser(configfile)
if not os.path.exists(configfile):
continue
ini_file = ConfigParser()
ini_file.read(configfile)
section = "nodeenv"
if not ini_file.has_section(section):
continue
for attr, val in iteritems(vars(cls)):
if attr.startswith('_') or not \
ini_file.has_option(section, attr):
continue
if isinstance(val, bool):
val = ini_file.getboolean(section, attr)
else:
val = ini_file.get(section, attr)
if verbose:
print('CONFIG {0}: {1} = {2}'.format(
os.path.basename(configfile), attr, val))
setattr(cls, attr, val)
if os.path.exists(".node-version"):
with open(".node-version", "r") as v_file:
setattr(cls, "node", v_file.readlines(1)[0].strip())
@classmethod
def _dump(cls):
"""
Print defaults for the README.
"""
print(" [nodeenv]")
print(" " + "\n ".join(
"%s = %s" % (k, v) for k, v in sorted(iteritems(vars(cls)))
if not k.startswith('_')))
Config._default = dict(
(attr, val) for attr, val in iteritems(vars(Config))
if not attr.startswith('_')
)
def clear_output(out):
"""
Remove new-lines and
"""
return out.decode('utf-8').replace('\n', '')
def remove_env_bin_from_path(env, env_bin_dir):
"""
Remove bin directory of the current environment from PATH
"""
return env.replace(env_bin_dir + ':', '')
def node_version_from_args(args):
"""
Parse the node version from the argparse args
"""
if args.node == 'system':
out, err = subprocess.Popen(
["node", "--version"], stdout=subprocess.PIPE).communicate()
return parse_version(clear_output(out).replace('v', ''))
return parse_version(args.node)
def create_logger():
"""
Create logger for diagnostic
"""
# create logger
loggr = logging.getLogger("nodeenv")
loggr.setLevel(logging.INFO)
# monkey patch
def emit(self, record):
msg = self.format(record)
fs = "%s" if getattr(record, "continued", False) else "%s\n"
self.stream.write(fs % to_utf8(msg))
self.flush()
logging.StreamHandler.emit = emit
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter(fmt="%(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
loggr.addHandler(ch)
return loggr
logger = create_logger()
def make_parser():
"""
Make a command line argument parser.
"""
parser = argparse.ArgumentParser(
usage="%(prog)s [OPTIONS] DEST_DIR")
parser.add_argument(
'--version', action='version', version=nodeenv_version)
parser.add_argument(
'-n', '--node', dest='node', metavar='NODE_VER', default=Config.node,
help='The node.js version to use, e.g., '
'--node=0.4.3 will use the node-v0.4.3 '
'to create the new environment. '
'The default is last stable version (`latest`). '
'Use `lts` to use the latest LTS release. '
'Use `system` to use system-wide node.')
parser.add_argument(
'--mirror',
action="store", dest='mirror', default=Config.mirror,
help='Set mirror server of nodejs.org to download from.')
if not is_WIN:
parser.add_argument(
'-j', '--jobs', dest='jobs', default=Config.jobs,
help='Sets number of parallel commands at node.js compilation. '
'The default is 2 jobs.')
parser.add_argument(
'--load-average', dest='load_average',
help='Sets maximum load average for executing parallel commands '
'at node.js compilation.')
parser.add_argument(
'--without-ssl', dest='without_ssl',
action='store_true', default=Config.without_ssl,
help='Build node.js without SSL support')
parser.add_argument(
'--debug', dest='debug',
action='store_true', default=Config.debug,
help='Build debug variant of the node.js')
parser.add_argument(
'--profile', dest='profile',
action='store_true', default=Config.profile,
help='Enable profiling for node.js')
parser.add_argument(
'--make', '-m', dest='make_path',
metavar='MAKE_PATH',
help='Path to make command',
default=Config.make)
parser.add_argument(
'--source', dest='prebuilt',
action='store_false', default=Config.prebuilt,
help='Install node.js from the source')
parser.add_argument(
'-v', '--verbose',
action='store_true', dest='verbose', default=False,
help="Verbose mode")
parser.add_argument(
'-q', '--quiet',
action='store_true', dest='quiet', default=False,
help="Quiet mode")
parser.add_argument(
'-C', '--config-file', dest='config_file', default=None,
help="Load a different file than '~/.nodeenvrc'. "
"Pass an empty string for no config (use built-in defaults).")
parser.add_argument(
'-r', '--requirements',
dest='requirements', default='', metavar='FILENAME',
help='Install all the packages listed in the given requirements file.')
parser.add_argument(
'--prompt', dest='prompt',
help='Provides an alternative prompt prefix for this environment')
parser.add_argument(
'-l', '--list', dest='list',
action='store_true', default=False,
help='Lists available node.js versions')
parser.add_argument(
'--update', dest='update',
action='store_true', default=False,
help='Install npm packages from file without node')
parser.add_argument(
'--with-npm', dest='with_npm',
action='store_true', default=Config.with_npm,
help='Build without installing npm into the new virtual environment. '
'Required for node.js < 0.6.3. By default, the npm included with '
'node.js is used. Under Windows, this defaults to true.')
parser.add_argument(
'--npm', dest='npm',
metavar='NPM_VER', default=Config.npm,
help='The npm version to use, e.g., '
'--npm=0.3.18 will use the npm-0.3.18.tgz '
'tarball to install. '
'The default is last available version (`latest`).')
parser.add_argument(
'--no-npm-clean', dest='no_npm_clean',
action='store_true', default=False,
help='Skip the npm 0.x cleanup. Cleanup is enabled by default.')
parser.add_argument(
'--python-virtualenv', '-p', dest='python_virtualenv',
action='store_true', default=False,
help='Use current python virtualenv')
parser.add_argument(
'--clean-src', '-c', dest='clean_src',
action='store_true', default=False,
help='Remove "src" directory after installation')
parser.add_argument(
'--force', dest='force',
action='store_true', default=False,
help='Force installation in a pre-existing directory')
parser.add_argument(
'--prebuilt', dest='prebuilt',
action='store_true', default=Config.prebuilt,
help='Install node.js from prebuilt package (default)')
parser.add_argument(
'--ignore_ssl_certs', dest='ignore_ssl_certs',
action='store_true', default=Config.ignore_ssl_certs,
help='Ignore certificates for package downloads. - UNSAFE -')
parser.add_argument(
metavar='DEST_DIR', dest='env_dir', nargs='?',
help='Destination directory')
return parser
def parse_args(check=True):
"""
Parses command line arguments.
Set `check` to False to skip validation checks.
"""
parser = make_parser()
args = parser.parse_args()
if args.config_file is None:
args.config_file = ["./tox.ini", "./setup.cfg", "~/.nodeenvrc"]
elif not args.config_file:
args.config_file = []
else:
# Make sure that explicitly provided files exist
if not os.path.exists(args.config_file):
parser.error("Config file '{0}' doesn't exist!".format(
args.config_file))
args.config_file = [args.config_file]
if not check:
return args
if not args.list:
if not args.python_virtualenv and not args.env_dir:
parser.error('You must provide a DEST_DIR or '
'use current python virtualenv')
return args
def mkdir(path):
"""
Create directory
"""
if not os.path.exists(path):
logger.debug(' * Creating: %s ... ', path, extra=dict(continued=True))
os.makedirs(path)
logger.debug('done.')
else:
logger.debug(' * Directory %s already exists', path)
def make_executable(filename):
mode_0755 = (stat.S_IRWXU | stat.S_IXGRP |
stat.S_IRGRP | stat.S_IROTH | stat.S_IXOTH)
os.chmod(filename, mode_0755)
# noinspection PyArgumentList
def writefile(dest, content, overwrite=True, append=False):
"""
Create file and write content in it
"""
content = to_utf8(content)
if is_PY3 and type(content) != bytes:
content = bytes(content, 'utf-8')
if not os.path.exists(dest):
logger.debug(' * Writing %s ... ', dest, extra=dict(continued=True))
with open(dest, 'wb') as f:
f.write(content)
make_executable(dest)
logger.debug('done.')
return
else:
with open(dest, 'rb') as f:
c = f.read()
if content in c:
logger.debug(' * Content %s already in place', dest)
return
if not overwrite:
logger.info(' * File %s exists with different content; '
' not overwriting', dest)
return
if append:
logger.info(' * Appending data to %s', dest)
with open(dest, 'ab') as f:
f.write(content)
return
logger.info(' * Overwriting %s with new content', dest)
with open(dest, 'wb') as f:
f.write(content)
def callit(cmd, show_stdout=True, in_shell=False,
cwd=None, extra_env=None):
"""
Execute cmd line in sub-shell
"""
all_output = []
cmd_parts = []
for part in cmd:
if len(part) > 45:
part = part[:20] + "..." + part[-20:]
if ' ' in part or '\n' in part or '"' in part or "'" in part:
part = '"%s"' % part.replace('"', '\\"')
cmd_parts.append(part)
cmd_desc = ' '.join(cmd_parts)
logger.debug(" ** Running command %s" % cmd_desc)
if in_shell:
cmd = ' '.join(cmd)
# output
stdout = subprocess.PIPE
# env
if extra_env:
env = os.environ.copy()
if extra_env:
env.update(extra_env)
else:
env = None
# execute
try:
proc = subprocess.Popen(
cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
cwd=cwd, env=env, shell=in_shell)
except Exception:
e = sys.exc_info()[1]
logger.error("Error %s while executing command %s" % (e, cmd_desc))
raise
stdout = proc.stdout
while stdout:
line = stdout.readline()
if not line:
break
try:
if is_WIN:
line = line.decode('mbcs').rstrip()
else:
line = line.decode('utf8').rstrip()
except UnicodeDecodeError:
line = line.decode('cp866').rstrip()
all_output.append(line)
if show_stdout:
logger.info(line)
proc.wait()
# error handler
if proc.returncode:
if show_stdout:
for s in all_output:
logger.critical(s)
raise OSError("Command %s failed with error code %s"
% (cmd_desc, proc.returncode))
return proc.returncode, all_output
def get_root_url(version):
if parse_version(version) > parse_version("0.5.0"):
return '%s/v%s/' % (src_base_url, version)
else:
return src_base_url
def is_x86_64_musl():
return sysconfig.get_config_var('HOST_GNU_TYPE') == 'x86_64-pc-linux-musl'
def get_node_bin_url(version):
archmap = {
'x86': 'x86', # Windows Vista 32
'i686': 'x86',
'x86_64': 'x64', # Linux Ubuntu 64
'amd64': 'x64', # FreeBSD 64bits
'AMD64': 'x64', # Windows Server 2012 R2 (x64)
'armv6l': 'armv6l', # arm
'armv7l': 'armv7l',
'armv8l': 'armv7l',
'aarch64': 'arm64',
'arm64': 'arm64',
'arm64/v8': 'arm64',
'armv8': 'arm64',
'armv8.4': 'arm64',
'ppc64le': 'ppc64le', # Power PC
's390x': 's390x', # IBM S390x
}
sysinfo = {
'system': platform.system().lower(),
'arch': archmap[platform.machine()],
}
if is_WIN or is_CYGWIN:
postfix = '-win-%(arch)s.zip' % sysinfo
elif is_x86_64_musl():
postfix = '-linux-x64-musl.tar.gz'
else:
postfix = '-%(system)s-%(arch)s.tar.gz' % sysinfo
filename = 'node-v%s%s' % (version, postfix)
return get_root_url(version) + filename
def get_node_src_url(version):
tar_name = 'node-v%s.tar.gz' % version
return get_root_url(version) + tar_name
@contextlib.contextmanager
def tarfile_open(*args, **kwargs):
"""Compatibility layer because py26."""
tf = tarfile.open(*args, **kwargs)
try:
yield tf
finally:
tf.close()
def download_node_src(node_url, src_dir, args):
"""
Download source code
"""
logger.info('.', extra=dict(continued=True))
try:
dl_contents = io.BytesIO(urlopen(node_url).read())
except IncompleteRead as e:
logger.warning('Incomplete read while reading'
'from {}'.format(node_url))
dl_contents = e.partial
logger.info('.', extra=dict(continued=True))
if is_WIN or is_CYGWIN:
ctx = zipfile.ZipFile(dl_contents)
members = operator.methodcaller('namelist')
member_name = lambda s: s # noqa: E731
else:
ctx = tarfile_open(fileobj=dl_contents)
members = operator.methodcaller('getmembers')
member_name = operator.attrgetter('name')
with ctx as archive:
node_ver = re.escape(args.node)
rexp_string = r"node-v%s[^/]*/(README\.md|CHANGELOG\.md|LICENSE)"\
% node_ver
extract_list = [
member
for member in members(archive)
if re.match(rexp_string, member_name(member)) is None
]
archive.extractall(src_dir, extract_list)
def urlopen(url):
home_url = "https://github.com/ekalinin/nodeenv/"
headers = {'User-Agent': 'nodeenv/%s (%s)' % (nodeenv_version, home_url)}
req = urllib2.Request(url, None, headers)
if ignore_ssl_certs:
# py27: protocol required, py3: optional
# https://github.com/ekalinin/nodeenv/issues/296
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.verify_mode = ssl.CERT_NONE
return urllib2.urlopen(req, context=context)
return urllib2.urlopen(req)
# ---------------------------------------------------------
# Virtual environment functions
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
try:
shutil.copytree(s, d, symlinks, ignore)
except OSError:
copytree(s, d, symlinks, ignore)
else:
if os.path.islink(s):
# copy link only if it not exists. #189
if not os.path.islink(d):
os.symlink(os.readlink(s), d)
else:
shutil.copy2(s, d)
def copy_node_from_prebuilt(env_dir, src_dir, node_version):
"""
Copy prebuilt binaries into environment
"""
logger.info('.', extra=dict(continued=True))
if is_WIN:
dest = join(env_dir, 'Scripts')
mkdir(dest)
elif is_CYGWIN:
dest = join(env_dir, 'bin')
mkdir(dest)
# write here to avoid https://bugs.python.org/issue35650
writefile(join(env_dir, 'bin', 'node'), CYGWIN_NODE)
else:
dest = env_dir
src_folder_tpl = src_dir + to_utf8('/node-v%s*' % node_version)
src_folder, = glob.glob(src_folder_tpl)
copytree(src_folder, dest, True)
if is_CYGWIN:
for filename in ('npm', 'npx', 'node.exe'):
filename = join(env_dir, 'bin', filename)
if os.path.exists(filename):
make_executable(filename)
logger.info('.', extra=dict(continued=True))
def build_node_from_src(env_dir, src_dir, node_src_dir, args):
env = {}
make_param_names = ['load-average', 'jobs']
make_param_values = map(
lambda x: getattr(args, x.replace('-', '_')),
make_param_names)
make_opts = [
'--{0}={1}'.format(name, value)
if len(value) > 0 else '--{0}'.format(name)
for name, value in zip(make_param_names, make_param_values)
if value is not None
]
if getattr(sys.version_info, 'major', sys.version_info[0]) > 2:
# Currently, the node.js build scripts are using python2.*,
# therefore we need to temporarily point python exec to the
# python 2.* version in this case.
try:
_, which_python2_output = callit(
['which', 'python2'], args.verbose, True, node_src_dir, env
)
python2_path = which_python2_output[0]
except (OSError, IndexError):
raise OSError(
'Python >=3.0 virtualenv detected, but no python2 '
'command (required for building node.js) was found'
)
logger.debug(' * Temporarily pointing python to %s', python2_path)
node_tmpbin_dir = join(src_dir, 'tmpbin')
node_tmpbin_link = join(node_tmpbin_dir, 'python')
mkdir(node_tmpbin_dir)
if not os.path.exists(node_tmpbin_link):
callit(['ln', '-s', python2_path, node_tmpbin_link])
env['PATH'] = '{}:{}'.format(node_tmpbin_dir,
os.environ.get('PATH', ''))
conf_cmd = [
'./configure',
'--prefix=%s' % pipes.quote(env_dir)
]
if args.without_ssl:
conf_cmd.append('--without-ssl')
if args.debug:
conf_cmd.append('--debug')
if args.profile:
conf_cmd.append('--profile')
make_cmd = args.make_path
callit(conf_cmd, args.verbose, True, node_src_dir, env)
logger.info('.', extra=dict(continued=True))
callit([make_cmd] + make_opts, args.verbose, True, node_src_dir, env)
logger.info('.', extra=dict(continued=True))
callit([make_cmd + ' install'], args.verbose, True, node_src_dir, env)
def install_node(env_dir, src_dir, args):
"""
Download source code for node.js, unpack it
and install it in virtual environment.
"""
try:
install_node_wrapped(env_dir, src_dir, args)
except BaseException:
# this restores the newline suppressed by continued=True
logger.info('')
raise
def install_node_wrapped(env_dir, src_dir, args):
env_dir = abspath(env_dir)
node_src_dir = join(src_dir, to_utf8('node-v%s' % args.node))
src_type = "prebuilt" if args.prebuilt else "source"
logger.info(' * Install %s node (%s) ' % (src_type, args.node),
extra=dict(continued=True))
if args.prebuilt:
node_url = get_node_bin_url(args.node)
else:
node_url = get_node_src_url(args.node)
# get src if not downloaded yet
if not os.path.exists(node_src_dir):
try:
download_node_src(node_url, src_dir, args)
except urllib2.HTTPError:
if "arm64" in node_url:
# if arm64 not found, try x64
download_node_src(node_url.replace('arm64', 'x64'),
src_dir, args)
logger.info('.', extra=dict(continued=True))
if args.prebuilt:
copy_node_from_prebuilt(env_dir, src_dir, args.node)
else:
build_node_from_src(env_dir, src_dir, node_src_dir, args)
logger.info(' done.')
def install_npm(env_dir, _src_dir, args):
"""
Download source code for npm, unpack it
and install it in virtual environment.
"""
logger.info(' * Install npm.js (%s) ... ' % args.npm,
extra=dict(continued=True))
env = dict(
os.environ,
clean='no' if args.no_npm_clean else 'yes',
npm_install=args.npm,
)
proc = subprocess.Popen(
(
'bash', '-c',
'. {0} && npm install -g npm@{1}'.format(
pipes.quote(join(env_dir, 'bin', 'activate')),
args.npm,
)
),
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
out, _ = proc.communicate()
if args.verbose:
logger.info(out)
logger.info('done.')
def install_npm_win(env_dir, src_dir, args):
"""
Download source code for npm, unpack it
and install it in virtual environment.
"""
logger.info(' * Install npm.js (%s) ... ' % args.npm,
extra=dict(continued=True))
npm_url = 'https://github.com/npm/cli/archive/v%s.zip' % args.npm
npm_contents = io.BytesIO(urlopen(npm_url).read())
bin_path = join(env_dir, 'Scripts')
node_modules_path = join(bin_path, 'node_modules', 'npm')
if os.path.exists(node_modules_path):
shutil.rmtree(node_modules_path)
if os.path.exists(join(bin_path, 'npm.cmd')):
os.remove(join(bin_path, 'npm.cmd'))
if os.path.exists(join(bin_path, 'npm-cli.js')):
os.remove(join(bin_path, 'npm-cli.js'))
with zipfile.ZipFile(npm_contents, 'r') as zipf:
zipf.extractall(src_dir)
npm_ver = 'cli-%s' % args.npm
shutil.copytree(join(src_dir, npm_ver), node_modules_path)
shutil.copy(join(src_dir, npm_ver, 'bin', 'npm.cmd'),
join(bin_path, 'npm.cmd'))
shutil.copy(join(src_dir, npm_ver, 'bin', 'npm-cli.js'),
join(bin_path, 'npm-cli.js'))
if is_CYGWIN:
shutil.copy(join(bin_path, 'npm-cli.js'),
join(env_dir, 'bin', 'npm-cli.js'))
shutil.copytree(join(bin_path, 'node_modules'),
join(env_dir, 'bin', 'node_modules'))
npm_gh_url = 'https://raw.githubusercontent.com/npm/cli'
npm_bin_url = '{}/{}/bin/npm'.format(npm_gh_url, args.npm)
writefile(join(env_dir, 'bin', 'npm'), urlopen(npm_bin_url).read())
def install_packages(env_dir, args):
"""
Install node.js packages via npm
"""
logger.info(' * Install node.js packages ... ',
extra=dict(continued=True))
packages = [package.strip() for package in
open(args.requirements).readlines()]
activate_path = join(env_dir, 'bin', 'activate')
real_npm_ver = args.npm if args.npm.count(".") == 2 else args.npm + ".0"
if args.npm == "latest" or real_npm_ver >= "1.0.0":
cmd = '. ' + pipes.quote(activate_path) + \
' && npm install -g %(pack)s'
else:
cmd = '. ' + pipes.quote(activate_path) + \
' && npm install %(pack)s' + \
' && npm activate %(pack)s'
for package in packages:
if not package:
continue
callit(cmd=[
cmd % {"pack": package}], show_stdout=args.verbose, in_shell=True)
logger.info('done.')
def install_activate(env_dir, args):
"""
Install virtual environment activation script
"""
if is_WIN:
files = {
'activate.bat': ACTIVATE_BAT,
"deactivate.bat": DEACTIVATE_BAT,
"Activate.ps1": ACTIVATE_PS1
}
bin_dir = join(env_dir, 'Scripts')
shim_node = join(bin_dir, "node.exe")
shim_nodejs = join(bin_dir, "nodejs.exe")
else:
files = {
'activate': ACTIVATE_SH,
'activate.fish': ACTIVATE_FISH,
'shim': SHIM
}
bin_dir = join(env_dir, 'bin')
shim_node = join(bin_dir, "node")
shim_nodejs = join(bin_dir, "nodejs")
if is_CYGWIN:
mkdir(bin_dir)
if args.node == "system":
files["node"] = SHIM
mod_dir = join('lib', 'node_modules')
prompt = args.prompt or '(%s)' % os.path.basename(os.path.abspath(env_dir))
if args.node == "system":
env = os.environ.copy()
env.update({'PATH': remove_env_bin_from_path(env['PATH'], bin_dir)})
for candidate in ("nodejs", "node"):
which_node_output, _ = subprocess.Popen(
["which", candidate],
stdout=subprocess.PIPE, env=env).communicate()
shim_node = clear_output(which_node_output)
if shim_node:
break
assert shim_node, "Did not find nodejs or node system executable"
for name, content in files.items():
file_path = join(bin_dir, name)
content = content.replace('__NODE_VIRTUAL_PROMPT__', prompt)
content = content.replace('__NODE_VIRTUAL_ENV__',
os.path.abspath(env_dir))
content = content.replace('__SHIM_NODE__', shim_node)
content = content.replace('__BIN_NAME__', os.path.basename(bin_dir))
content = content.replace('__MOD_NAME__', mod_dir)
if is_CYGWIN:
_, cyg_bin_dir = callit(
['cygpath', '-w', os.path.abspath(bin_dir)],
show_stdout=False, in_shell=False)
content = content.replace('__NPM_CONFIG_PREFIX__', cyg_bin_dir[0])
else:
content = content.replace('__NPM_CONFIG_PREFIX__',
'$NODE_VIRTUAL_ENV')
# if we call in the same environment:
# $ nodeenv -p --prebuilt
# $ nodeenv -p --node=system
# we should get `bin/node` not as binary+string.
# `bin/activate` should be appended if we're inside
# existing python's virtual environment
need_append = False
if args.python_virtualenv:
disable_prompt = DISABLE_PROMPT.get(name, '')
enable_prompt = ENABLE_PROMPT.get(name, '')
content = disable_prompt + content + enable_prompt
need_append = bool(disable_prompt)
writefile(file_path, content, append=need_append)
if not os.path.exists(shim_nodejs):
if is_WIN:
try:
callit(['mklink', shim_nodejs, 'node.exe'], True, True)
except OSError:
logger.error('Error: Failed to create nodejs.exe link')
else:
os.symlink("node", shim_nodejs)
def set_predeactivate_hook(env_dir):
if not is_WIN:
with open(join(env_dir, 'bin', 'predeactivate'), 'a') as hook:
hook.write(PREDEACTIVATE_SH)
def create_environment(env_dir, args):
"""
Creates a new environment in ``env_dir``.
"""
if os.path.exists(env_dir) and not args.python_virtualenv:
logger.info(' * Environment already exists: %s', env_dir)
if not args.force:
sys.exit(2)
src_dir = to_utf8(abspath(join(env_dir, 'src')))
mkdir(src_dir)
if args.node != "system":
install_node(env_dir, src_dir, args)
else:
mkdir(join(env_dir, 'bin'))
mkdir(join(env_dir, 'lib'))
mkdir(join(env_dir, 'lib', 'node_modules'))
# activate script install must be
# before npm install, npm use activate
# for install
install_activate(env_dir, args)
if node_version_from_args(args) < parse_version("0.6.3") or args.with_npm:
instfunc = install_npm_win if is_WIN or is_CYGWIN else install_npm
instfunc(env_dir, src_dir, args)
if args.requirements:
install_packages(env_dir, args)
if args.python_virtualenv:
set_predeactivate_hook(env_dir)
# Cleanup
if args.clean_src:
shutil.rmtree(src_dir)