-
Notifications
You must be signed in to change notification settings - Fork 425
/
build.py
2574 lines (2226 loc) · 122 KB
/
build.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
'''
Module that does most of the heavy lifting for the ``conda build`` command.
'''
from __future__ import absolute_import, division, print_function
from collections import deque, OrderedDict
import fnmatch
from glob import glob
import io
import json
import libarchive
import os
from os.path import isdir, isfile, islink, join, dirname
import random
import re
import shutil
import stat
import string
import subprocess
import sys
import time
from tempfile import NamedTemporaryFile
# this is to compensate for a requests idna encoding error. Conda is a better place to fix,
# eventually
# exception is raises: "LookupError: unknown encoding: idna"
# http://stackoverflow.com/a/13057751/1170370
import encodings.idna # NOQA
from bs4 import UnicodeDammit
import yaml
try:
from conda.base.constants import CONDA_TARBALL_EXTENSIONS
except Exception:
from conda.base.constants import CONDA_TARBALL_EXTENSION
CONDA_TARBALL_EXTENSIONS = (CONDA_TARBALL_EXTENSION,)
# used to get version
from .conda_interface import env_path_backup_var_exists, conda_45, conda_46
from .conda_interface import PY3
from .conda_interface import prefix_placeholder
from .conda_interface import TemporaryDirectory
from .conda_interface import VersionOrder
from .conda_interface import text_type
from .conda_interface import CrossPlatformStLink
from .conda_interface import PathType, FileMode
from .conda_interface import EntityEncoder
from .conda_interface import get_rc_urls
from .conda_interface import url_path
from .conda_interface import root_dir
from .conda_interface import conda_private
from .conda_interface import MatchSpec
from .conda_interface import reset_context
from .conda_interface import context
from .conda_interface import UnsatisfiableError
from .conda_interface import NoPackagesFoundError
from .conda_interface import CondaError
from .conda_interface import pkgs_dirs
from .utils import env_var, tmp_chdir
from conda_build import __version__
from conda_build import environ, source, tarcheck, utils
from conda_build.index import get_build_index, update_index
from conda_build.render import (output_yaml, bldpkg_path, render_recipe, reparse, finalize_metadata,
distribute_variants, expand_outputs, try_download,
add_upstream_pins, execute_download_actions)
import conda_build.os_utils.external as external
from conda_build.metadata import FIELDS, MetaData, default_structs
from conda_build.post import (post_process, post_build,
fix_permissions, get_build_metadata)
from conda_build.exceptions import indent, DependencyNeedsBuildingError, CondaBuildException
from conda_build.variants import (set_language_env_vars, dict_of_lists_to_list_of_dicts,
get_package_variants)
from conda_build.create_test import create_all_test_files
import conda_build.noarch_python as noarch_python
from conda import __version__ as conda_version
from conda_build import __version__ as conda_build_version
if sys.platform == 'win32':
import conda_build.windows as windows
if 'bsd' in sys.platform:
shell_path = '/bin/sh'
elif utils.on_win:
shell_path = 'bash'
else:
shell_path = '/bin/bash'
def stats_key(metadata, desc):
# get the build string from whatever conda-build makes of the configuration
used_loop_vars = metadata.get_used_loop_vars()
build_vars = '-'.join([k + '_' + str(metadata.config.variant[k]) for k in used_loop_vars
if k != 'target_platform'])
# kind of a special case. Target platform determines a lot of output behavior, but may not be
# explicitly listed in the recipe.
tp = metadata.config.variant.get('target_platform')
if tp and tp != metadata.config.subdir and 'target_platform' not in build_vars:
build_vars += '-target_' + tp
key = [metadata.name(), metadata.version()]
if build_vars:
key.append(build_vars)
key = "-".join(key)
key = desc + key
return key
def seconds_to_text(secs):
m, s = divmod(secs, 60)
h, m = divmod(int(m), 60)
return "{:d}:{:02d}:{:04.1f}".format(h, m, s)
def log_stats(stats_dict, descriptor):
print("\nResource usage statistics from {}:".format(descriptor))
print(" Process count: {}".format(stats_dict.get('processes', 1)))
if stats_dict.get('cpu_sys'):
print(" CPU time: Sys={}, User={}".format(seconds_to_text(stats_dict.get('cpu_sys', 0)),
seconds_to_text(stats_dict.get('cpu_user', 0))))
else:
print(" CPU time: unavailable")
if stats_dict.get('rss'):
print(" Memory: {}".format(utils.bytes2human(stats_dict.get('rss', 0))))
else:
print(" Memory: unavailable")
print(" Disk usage: {}".format(utils.bytes2human(stats_dict['disk'])))
print(" Time elapsed: {}\n".format(seconds_to_text(stats_dict['elapsed'])))
def create_post_scripts(m):
'''
Create scripts to run after build step
'''
recipe_dir = (m.path or
m.meta.get('extra', {}).get('parent_recipe', {}).get('path', ""))
ext = '.bat' if utils.on_win else '.sh'
for tp in 'pre-link', 'post-link', 'pre-unlink':
# To have per-output link scripts they must be prefixed by the output name or be explicitly
# specified in the build section
is_output = 'package:' not in m.get_recipe_text()
scriptname = tp
if is_output:
if m.meta.get('build', {}).get(tp, ''):
scriptname = m.meta['build'][tp]
else:
scriptname = m.name() + '-' + tp
scriptname += ext
dst_name = '.' + m.name() + '-' + tp + ext
src = join(recipe_dir, scriptname)
if isfile(src):
dst_dir = join(m.config.host_prefix,
'Scripts' if m.config.host_subdir.startswith('win-') else 'bin')
if not isdir(dst_dir):
os.makedirs(dst_dir, 0o775)
dst = join(dst_dir, dst_name)
utils.copy_into(src, dst, m.config.timeout, locking=m.config.locking)
os.chmod(dst, 0o775)
def have_prefix_files(files, prefix):
'''
Yields files that contain the current prefix in them, and modifies them
to replace the prefix with a placeholder.
:param files: Filenames to check for instances of prefix
:type files: list of tuples containing strings (prefix, mode, filename)
'''
prefix_bytes = prefix.encode(utils.codec)
prefix_placeholder_bytes = prefix_placeholder.encode(utils.codec)
if utils.on_win:
forward_slash_prefix = prefix.replace('\\', '/')
forward_slash_prefix_bytes = forward_slash_prefix.encode(utils.codec)
double_backslash_prefix = prefix.replace('\\', '\\\\')
double_backslash_prefix_bytes = double_backslash_prefix.encode(utils.codec)
for f in files:
if f.endswith(('.pyc', '.pyo')):
continue
path = join(prefix, f)
if not isfile(path):
continue
if sys.platform != 'darwin' and islink(path):
# OSX does not allow hard-linking symbolic links, so we cannot
# skip symbolic links (as we can on Linux)
continue
# dont try to mmap an empty file
if os.stat(path).st_size == 0:
continue
try:
fi = open(path, 'rb+')
except IOError:
log = utils.get_logger(__name__)
log.warn("failed to open %s for detecting prefix. Skipping it." % f)
continue
try:
mm = utils.mmap_mmap(fi.fileno(), 0, tagname=None, flags=utils.mmap_MAP_PRIVATE)
except OSError:
mm = fi.read()
mode = 'binary' if mm.find(b'\x00') != -1 else 'text'
if mode == 'text':
if not utils.on_win and mm.find(prefix_bytes) != -1:
# Use the placeholder for maximal backwards compatibility, and
# to minimize the occurrences of usernames appearing in built
# packages.
data = mm[:]
mm.close()
fi.close()
rewrite_file_with_new_prefix(path, data, prefix_bytes, prefix_placeholder_bytes)
fi = open(path, 'rb+')
mm = utils.mmap_mmap(fi.fileno(), 0, tagname=None, flags=utils.mmap_MAP_PRIVATE)
if mm.find(prefix_bytes) != -1:
yield (prefix, mode, f)
if utils.on_win and mm.find(forward_slash_prefix_bytes) != -1:
# some windows libraries use unix-style path separators
yield (forward_slash_prefix, mode, f)
elif utils.on_win and mm.find(double_backslash_prefix_bytes) != -1:
# some windows libraries have double backslashes as escaping
yield (double_backslash_prefix, mode, f)
if mm.find(prefix_placeholder_bytes) != -1:
yield (prefix_placeholder, mode, f)
mm.close()
fi.close()
def rewrite_file_with_new_prefix(path, data, old_prefix, new_prefix):
# Old and new prefix should be bytes
st = os.stat(path)
data = data.replace(old_prefix, new_prefix)
# Save as
with open(path, 'wb') as fo:
fo.write(data)
os.chmod(path, stat.S_IMODE(st.st_mode) | stat.S_IWUSR) # chmod u+w
return data
def _copy_top_level_recipe(path, config, dest_dir, destination_subdir=None):
files = utils.rec_glob(path, "*")
file_paths = sorted([f.replace(path + os.sep, '') for f in files])
# when this actually has a value, we're copying the top-level recipe into a subdirectory,
# so that we have record of what parent recipe produced subpackages.
if destination_subdir:
dest_dir = join(dest_dir, destination_subdir)
else:
# exclude meta.yaml because the json dictionary captures its content
file_paths = [f for f in file_paths if not (f == 'meta.yaml' or
f == 'conda_build_config.yaml')]
file_paths = utils.filter_files(file_paths, path)
for f in file_paths:
utils.copy_into(join(path, f), join(dest_dir, f),
timeout=config.timeout,
locking=config.locking, clobber=True)
def _copy_output_recipe(m, dest_dir):
src_dir = m.meta.get('extra', {}).get('parent_recipe', {}).get('path')
if src_dir:
_copy_top_level_recipe(src_dir, m.config, dest_dir, 'parent')
this_output = m.get_rendered_output(m.name()) or {}
install_script = this_output.get('script')
build_inputs = []
inputs = [install_script] + build_inputs
file_paths = [script for script in inputs if script]
file_paths = utils.filter_files(file_paths, src_dir)
else:
file_paths = []
for f in file_paths:
utils.copy_into(join(src_dir, f), join(dest_dir, f),
timeout=m.config.timeout,
locking=m.config.locking, clobber=True)
def copy_recipe(m):
if m.config.include_recipe and m.include_recipe():
# store the rendered meta.yaml file, plus information about where it came from
# and what version of conda-build created it
recipe_dir = join(m.config.info_dir, 'recipe')
try:
os.makedirs(recipe_dir)
except:
pass
if os.path.isdir(m.path):
_copy_top_level_recipe(m.path, m.config, recipe_dir)
original_recipe = m.meta_path
# it's a subpackage.
else:
_copy_output_recipe(m, recipe_dir)
original_recipe = ""
output_metadata = m.copy()
# hard code the build string, so that tests don't get it mixed up
build = output_metadata.meta.get('build', {})
build['string'] = output_metadata.build_id()
output_metadata.meta['build'] = build
# just for lack of confusion, don't show outputs in final rendered recipes
if 'outputs' in output_metadata.meta:
del output_metadata.meta['outputs']
if 'parent_recipe' in output_metadata.meta.get('extra', {}):
del output_metadata.meta['extra']['parent_recipe']
utils.sort_list_in_nested_structure(output_metadata.meta,
('build/script', 'test/commands'))
rendered = output_yaml(output_metadata)
if original_recipe:
with open(original_recipe, 'rb') as f:
original_recipe_text = UnicodeDammit(f.read()).unicode_markup
if not original_recipe or not original_recipe_text == rendered:
with open(join(recipe_dir, "meta.yaml"), 'w') as f:
f.write("# This file created by conda-build {}\n".format(__version__))
if original_recipe:
f.write("# meta.yaml template originally from:\n")
f.write("# " + source.get_repository_info(m.path) + "\n")
f.write("# ------------------------------------------------\n\n")
f.write(rendered)
if original_recipe:
utils.copy_into(original_recipe, os.path.join(recipe_dir, 'meta.yaml.template'),
timeout=m.config.timeout, locking=m.config.locking, clobber=True)
# dump the full variant in use for this package to the recipe folder
with open(os.path.join(recipe_dir, 'conda_build_config.yaml'), 'w') as f:
yaml.dump(m.config.variant, f)
def copy_readme(m):
readme = m.get_value('about/readme')
if readme:
src = join(m.config.work_dir, readme)
if not isfile(src):
sys.exit("Error: no readme file: %s" % readme)
dst = join(m.config.info_dir, readme)
utils.copy_into(src, dst, m.config.timeout, locking=m.config.locking)
if os.path.split(readme)[1] not in {"README.md", "README.rst", "README"}:
print("WARNING: anaconda.org only recognizes about/readme "
"as README.md and README.rst", file=sys.stderr)
def copy_license(m):
license_file = m.get_value('about/license_file')
if license_file:
src_file = join(m.config.work_dir, license_file)
if not os.path.isfile(src_file):
src_file = os.path.join(m.path, license_file)
if os.path.isfile(src_file):
utils.copy_into(src_file,
join(m.config.info_dir, 'LICENSE.txt'), m.config.timeout,
locking=m.config.locking)
print("Packaged license file.")
else:
raise ValueError("License file given in about/license_file ({}) does not exist in "
"source root dir or in recipe root dir (with meta.yaml)".format(src_file))
def copy_recipe_log(m):
# the purpose of this file is to capture some change history metadata that may tell people
# why a given build was changed the way that it was
log_file = m.get_value('about/recipe_log_file') or "recipe_log.json"
# look in recipe folder first
src_file = os.path.join(m.path, log_file)
if not os.path.isfile(src_file):
src_file = join(m.config.work_dir, log_file)
if os.path.isfile(src_file):
utils.copy_into(src_file,
join(m.config.info_dir, 'recipe_log.json'), m.config.timeout,
locking=m.config.locking)
def copy_test_source_files(m, destination):
src_dir = ''
if os.listdir(m.config.work_dir):
src_dir = m.config.work_dir
elif hasattr(m.config, 'recipe_dir') and m.config.recipe_dir:
src_dir = os.path.join(m.config.recipe_dir, 'info', 'test')
src_dirs = [src_dir]
if os.path.isdir(os.path.join(src_dir, 'parent')):
src_dirs.append(os.path.join(src_dir, 'parent'))
for src_dir in src_dirs:
if src_dir and os.path.isdir(src_dir) and src_dir != destination:
for pattern in utils.ensure_list(m.get_value('test/source_files', [])):
if utils.on_win and '\\' in pattern:
raise RuntimeError("test/source_files paths must use / "
"as the path delimiter on Windows")
files = glob(join(src_dir, pattern))
if not files:
msg = "Did not find any source_files for test with pattern {0}"
raise RuntimeError(msg.format(pattern))
for f in files:
try:
# disable locking to avoid locking a temporary directory (the extracted
# test folder)
utils.copy_into(f, f.replace(src_dir, destination), m.config.timeout,
locking=False, clobber=True)
except OSError as e:
log = utils.get_logger(__name__)
log.warn("Failed to copy {0} into test files. Error was: {1}".format(f,
str(e)))
for ext in '.pyc', '.pyo':
for f in utils.get_ext_files(destination, ext):
os.remove(f)
recipe_test_files = m.get_value('test/files')
if recipe_test_files:
orig_recipe_dir = m.path or m.meta.get('extra', {}).get('parent_recipe', {}).get('path')
for pattern in recipe_test_files:
files = glob(join(orig_recipe_dir, pattern))
for f in files:
basedir = orig_recipe_dir
if not os.path.isfile(f):
basedir = os.path.join(orig_recipe_dir, 'parent')
dest = f.replace(basedir, destination)
if f != dest:
utils.copy_into(f, f.replace(basedir, destination),
timeout=m.config.timeout, locking=m.config.locking,
clobber=True)
def write_hash_input(m):
recipe_input = m.get_hash_contents()
with open(os.path.join(m.config.info_dir, 'hash_input.json'), 'w') as f:
json.dump(recipe_input, f, indent=2)
def get_files_with_prefix(m, files, prefix):
files_with_prefix = sorted(have_prefix_files(files, prefix))
ignore_files = m.ignore_prefix_files()
ignore_types = set()
if not hasattr(ignore_files, "__iter__"):
if ignore_files is True:
ignore_types.update((FileMode.text.name, FileMode.binary.name))
ignore_files = []
if not m.get_value('build/detect_binary_files_with_prefix', True):
ignore_types.update((FileMode.binary.name,))
# files_with_prefix is a list of tuples containing (prefix_placeholder, file_type, file_path)
ignore_files.extend(
f[2] for f in files_with_prefix if f[1] in ignore_types and f[2] not in ignore_files)
files_with_prefix = [f for f in files_with_prefix if f[2] not in ignore_files]
return files_with_prefix
def detect_and_record_prefix_files(m, files, prefix):
files_with_prefix = get_files_with_prefix(m, files, prefix)
binary_has_prefix_files = m.binary_has_prefix_files()
text_has_prefix_files = m.has_prefix_files()
if files_with_prefix and not m.noarch:
if utils.on_win:
# Paths on Windows can contain spaces, so we need to quote the
# paths. Fortunately they can't contain quotes, so we don't have
# to worry about nested quotes.
fmt_str = '"%s" %s "%s"\n'
else:
# Don't do it everywhere because paths on Unix can contain quotes,
# and we don't have a good method of escaping, and because older
# versions of conda don't support quotes in has_prefix
fmt_str = '%s %s %s\n'
with open(join(m.config.info_dir, 'has_prefix'), 'w') as fo:
for pfix, mode, fn in files_with_prefix:
print("Detected hard-coded path in %s file %s" % (mode, fn))
fo.write(fmt_str % (pfix, mode, fn))
if mode == 'binary' and fn in binary_has_prefix_files:
binary_has_prefix_files.remove(fn)
elif mode == 'text' and fn in text_has_prefix_files:
text_has_prefix_files.remove(fn)
# make sure we found all of the files expected
errstr = ""
for f in text_has_prefix_files:
errstr += "Did not detect hard-coded path in %s from has_prefix_files\n" % f
for f in binary_has_prefix_files:
errstr += "Did not detect hard-coded path in %s from binary_has_prefix_files\n" % f
if errstr:
raise RuntimeError(errstr)
def sanitize_channel(channel):
return re.sub(r'\/t\/[a-zA-Z0-9\-]*\/', '/t/<TOKEN>/', channel)
def write_info_files_file(m, files):
entry_point_scripts = m.get_value('build/entry_points')
entry_point_script_names = get_entry_point_script_names(entry_point_scripts)
mode_dict = {'mode': 'w', 'encoding': 'utf-8'} if PY3 else {'mode': 'wb'}
with open(join(m.config.info_dir, 'files'), **mode_dict) as fo:
if m.noarch == 'python':
for f in sorted(files):
if f.find("site-packages") >= 0:
fo.write(f[f.find("site-packages"):] + '\n')
elif f.startswith("bin") and (f not in entry_point_script_names):
fo.write(f.replace("bin", "python-scripts") + '\n')
elif f.startswith("Scripts") and (f not in entry_point_script_names):
fo.write(f.replace("Scripts", "python-scripts") + '\n')
else:
fo.write(f + '\n')
else:
for f in sorted(files):
fo.write(f + '\n')
def write_link_json(m):
package_metadata = OrderedDict()
noarch_type = m.get_value('build/noarch')
if noarch_type:
noarch_dict = OrderedDict(type=text_type(noarch_type))
if text_type(noarch_type).lower() == "python":
entry_points = m.get_value('build/entry_points')
if entry_points:
noarch_dict['entry_points'] = entry_points
package_metadata['noarch'] = noarch_dict
preferred_env = m.get_value("build/preferred_env")
if preferred_env:
preferred_env_dict = OrderedDict(name=text_type(preferred_env))
executable_paths = m.get_value("build/preferred_env_executable_paths")
if executable_paths:
preferred_env_dict["executable_paths"] = executable_paths
package_metadata["preferred_env"] = preferred_env_dict
if package_metadata:
# The original name of this file was info/package_metadata_version.json, but we've
# now changed it to info/link.json. Still, we must indefinitely keep the key name
# package_metadata_version, or we break conda.
package_metadata["package_metadata_version"] = 1
with open(os.path.join(m.config.info_dir, "link.json"), 'w') as fh:
fh.write(json.dumps(package_metadata, sort_keys=True, indent=2, separators=(',', ': ')))
def write_about_json(m):
with open(join(m.config.info_dir, 'about.json'), 'w') as fo:
d = {}
for key in FIELDS["about"]:
value = m.get_value('about/%s' % key)
if value:
d[key] = value
if default_structs.get('about/%s' % key) == list:
d[key] = utils.ensure_list(value)
# for sake of reproducibility, record some conda info
d['conda_version'] = conda_version
d['conda_build_version'] = conda_build_version
# conda env will be in most, but not necessarily all installations.
# Don't die if we don't see it.
stripped_channels = []
for channel in get_rc_urls() + list(m.config.channel_urls):
stripped_channels.append(sanitize_channel(channel))
d['channels'] = stripped_channels
evars = ['CIO_TEST']
d['env_vars'] = {ev: os.getenv(ev, '<not set>') for ev in evars}
# this information will only be present in conda 4.2.10+
try:
d['conda_private'] = conda_private
except (KeyError, AttributeError):
pass
env = environ.Environment(root_dir)
d['root_pkgs'] = env.package_specs()
# Include the extra section of the metadata in the about.json
d['extra'] = m.get_section('extra')
json.dump(d, fo, indent=2, sort_keys=True)
def write_info_json(m):
info_index = m.info_index()
if m.pin_depends:
# Wtih 'strict' depends, we will have pinned run deps during rendering
if m.pin_depends == 'strict':
runtime_deps = m.meta.get('requirements', {}).get('run', [])
info_index['depends'] = runtime_deps
else:
runtime_deps = environ.get_pinned_deps(m, 'run')
with open(join(m.config.info_dir, 'requires'), 'w') as fo:
fo.write("""\
# This file as created when building:
#
# %s.tar.bz2 (on '%s')
#
# It can be used to create the runtime environment of this package using:
# $ conda create --name <env> --file <this file>
""" % (m.dist(), m.config.build_subdir))
for dist in sorted(runtime_deps + [' '.join(m.dist().rsplit('-', 2))]):
fo.write('%s\n' % '='.join(dist.split()))
# Deal with Python 2 and 3's different json module type reqs
mode_dict = {'mode': 'w', 'encoding': 'utf-8'} if PY3 else {'mode': 'wb'}
with open(join(m.config.info_dir, 'index.json'), **mode_dict) as fo:
json.dump(info_index, fo, indent=2, sort_keys=True)
def write_no_link(m, files):
no_link = m.get_value('build/no_link')
if no_link:
if not isinstance(no_link, list):
no_link = [no_link]
with open(join(m.config.info_dir, 'no_link'), 'w') as fo:
for f in files:
if any(fnmatch.fnmatch(f, p) for p in no_link):
fo.write(f + '\n')
def get_entry_point_script_names(entry_point_scripts):
scripts = []
for entry_point in entry_point_scripts:
cmd = entry_point[:entry_point.find("=")].strip()
if utils.on_win:
scripts.append("Scripts\\%s-script.py" % cmd)
scripts.append("Scripts\\%s.exe" % cmd)
else:
scripts.append("bin/%s" % cmd)
return scripts
def write_run_exports(m):
run_exports = m.meta.get('build', {}).get('run_exports', {})
if run_exports:
with open(os.path.join(m.config.info_dir, 'run_exports.json'), 'w') as f:
if not hasattr(run_exports, 'keys'):
run_exports = {'weak': run_exports}
for k in ('weak', 'strong'):
if k in run_exports:
run_exports[k] = utils.ensure_list(run_exports[k])
json.dump(run_exports, f)
def create_info_files(m, files, prefix):
'''
Creates the metadata files that will be stored in the built package.
:param m: Package metadata
:type m: Metadata
:param files: Paths to files to include in package
:type files: list of str
'''
if utils.on_win:
# make sure we use '/' path separators in metadata
files = [_f.replace('\\', '/') for _f in files]
if m.config.filename_hashing:
write_hash_input(m)
write_info_json(m) # actually index.json
write_about_json(m)
write_link_json(m)
write_run_exports(m)
copy_recipe(m)
copy_readme(m)
copy_license(m)
copy_recipe_log(m)
create_all_test_files(m, test_dir=join(m.config.info_dir, 'test'))
if m.config.copy_test_source_files:
copy_test_source_files(m, join(m.config.info_dir, 'test'))
write_info_files_file(m, files)
files_with_prefix = get_files_with_prefix(m, files, prefix)
checksums = create_info_files_json_v1(m, m.config.info_dir, prefix, files, files_with_prefix)
detect_and_record_prefix_files(m, files, prefix)
write_no_link(m, files)
sources = m.get_section('source')
if hasattr(sources, 'keys'):
sources = [sources]
with io.open(join(m.config.info_dir, 'git'), 'w', encoding='utf-8') as fo:
for src in sources:
if src.get('git_url'):
source.git_info(os.path.join(m.config.work_dir, src.get('folder', '')),
verbose=m.config.verbose, fo=fo)
if m.get_value('app/icon'):
utils.copy_into(join(m.path, m.get_value('app/icon')),
join(m.config.info_dir, 'icon.png'),
m.config.timeout, locking=m.config.locking)
return checksums
def get_short_path(m, target_file):
entry_point_script_names = get_entry_point_script_names(m.get_value('build/entry_points'))
if m.noarch == 'python':
if target_file.find("site-packages") >= 0:
return target_file[target_file.find("site-packages"):]
elif target_file.startswith("bin") and (target_file not in entry_point_script_names):
return target_file.replace("bin", "python-scripts")
elif target_file.startswith("Scripts") and (target_file not in entry_point_script_names):
return target_file.replace("Scripts", "python-scripts")
else:
return target_file
elif m.get_value('build/noarch_python', None):
return None
else:
return target_file
def has_prefix(short_path, files_with_prefix):
for prefix, mode, filename in files_with_prefix:
if short_path == filename:
return prefix, mode
return None, None
def is_no_link(no_link, short_path):
no_link = utils.ensure_list(no_link)
if any(fnmatch.fnmatch(short_path, p) for p in no_link):
return True
def get_inode_paths(files, target_short_path, prefix):
utils.ensure_list(files)
target_short_path_inode = os.lstat(join(prefix, target_short_path)).st_ino
hardlinked_files = [sp for sp in files
if os.lstat(join(prefix, sp)).st_ino == target_short_path_inode]
return sorted(hardlinked_files)
def path_type(path):
return PathType.softlink if islink(path) else PathType.hardlink
def build_info_files_json_v1(m, prefix, files, files_with_prefix):
no_link_files = m.get_value('build/no_link')
files_json = []
for fi in sorted(files):
prefix_placeholder, file_mode = has_prefix(fi, files_with_prefix)
path = os.path.join(prefix, fi)
short_path = get_short_path(m, fi)
if short_path:
short_path = short_path.replace('\\', '/').replace('\\\\', '/')
file_info = {
"_path": short_path,
"sha256": utils.sha256_checksum(path),
"size_in_bytes": os.path.getsize(path),
"path_type": path_type(path),
}
no_link = is_no_link(no_link_files, fi)
if no_link:
file_info["no_link"] = no_link
if prefix_placeholder and file_mode:
file_info["prefix_placeholder"] = prefix_placeholder
file_info["file_mode"] = file_mode
if file_info.get("path_type") == PathType.hardlink and CrossPlatformStLink.st_nlink(
join(prefix, fi)) > 1:
inode_paths = get_inode_paths(files, fi, prefix)
file_info["inode_paths"] = inode_paths
files_json.append(file_info)
return files_json
def create_info_files_json_v1(m, info_dir, prefix, files, files_with_prefix):
# fields: "_path", "sha256", "size_in_bytes", "path_type", "file_mode",
# "prefix_placeholder", "no_link", "inode_paths"
files_json_files = build_info_files_json_v1(m, prefix, files, files_with_prefix)
files_json_info = {
"paths_version": 1,
"paths": files_json_files,
}
# don't create info/paths.json file if this is an old noarch package
if not m.noarch_python:
with open(join(info_dir, 'paths.json'), "w") as files_json:
json.dump(files_json_info, files_json, sort_keys=True, indent=2, separators=(',', ': '),
cls=EntityEncoder)
# Return a dict of file: sha1sum. We could (but currently do not)
# use this to detect overlap and mutated overlap.
checksums = dict()
for file in files_json_files:
checksums[file['_path']] = file['sha256']
return checksums
def post_process_files(m, initial_prefix_files):
get_build_metadata(m)
create_post_scripts(m)
# this is new-style noarch, with a value of 'python'
if m.noarch != 'python':
utils.create_entry_points(m.get_value('build/entry_points'), config=m.config)
current_prefix_files = utils.prefix_files(prefix=m.config.host_prefix)
python = (m.config.build_python if os.path.isfile(m.config.build_python) else
m.config.host_python)
post_process(m.get_value('package/name'), m.get_value('package/version'),
sorted(current_prefix_files - initial_prefix_files),
prefix=m.config.host_prefix,
config=m.config,
preserve_egg_dir=bool(m.get_value('build/preserve_egg_dir')),
noarch=m.get_value('build/noarch'),
skip_compile_pyc=m.get_value('build/skip_compile_pyc'))
# The post processing may have deleted some files (like easy-install.pth)
current_prefix_files = utils.prefix_files(prefix=m.config.host_prefix)
new_files = sorted(current_prefix_files - initial_prefix_files)
new_files = utils.filter_files(new_files, prefix=m.config.host_prefix)
if any(m.config.meta_dir in join(m.config.host_prefix, f) for f in new_files):
meta_files = (tuple(f for f in new_files if m.config.meta_dir in
join(m.config.host_prefix, f)),)
sys.exit(indent("""Error: Untracked file(s) %s found in conda-meta directory.
This error usually comes from using conda in the build script. Avoid doing this, as it
can lead to packages that include their dependencies.""" % meta_files))
post_build(m, new_files, build_python=python)
entry_point_script_names = get_entry_point_script_names(m.get_value('build/entry_points'))
if m.noarch == 'python':
pkg_files = [fi for fi in new_files if fi not in entry_point_script_names]
else:
pkg_files = new_files
# the legacy noarch
if m.get_value('build/noarch_python'):
noarch_python.transform(m, new_files, m.config.host_prefix)
# new way: build/noarch: python
elif m.noarch == 'python':
noarch_python.populate_files(m, pkg_files, m.config.host_prefix, entry_point_script_names)
current_prefix_files = utils.prefix_files(prefix=m.config.host_prefix)
new_files = current_prefix_files - initial_prefix_files
fix_permissions(new_files, m.config.host_prefix)
return new_files
def bundle_conda(output, metadata, env, stats, **kw):
log = utils.get_logger(__name__)
log.info('Packaging %s', metadata.dist())
files = output.get('files', [])
# this is because without any requirements at all, we still need to have the host prefix exist
try:
os.makedirs(metadata.config.host_prefix)
except OSError:
pass
# Use script from recipe?
script = utils.ensure_list(metadata.get_value('build/script', None))
# need to treat top-level stuff specially. build/script in top-level stuff should not be
# re-run for an output with a similar name to the top-level recipe
is_output = 'package:' not in metadata.get_recipe_text()
top_build = metadata.get_top_level_recipe_without_outputs().get('build', {}) or {}
activate_script = metadata.activate_build_script
if (script and not output.get('script')) and (is_output or not top_build.get('script')):
# do add in activation, but only if it's not disabled
activate_script = metadata.config.activate
script = '\n'.join(script)
suffix = "bat" if utils.on_win else "sh"
script_fn = output.get('script') or 'output_script.{}'.format(suffix)
with open(os.path.join(metadata.config.work_dir, script_fn), 'w') as f:
f.write('\n')
f.write(script)
f.write('\n')
output['script'] = script_fn
if output.get('script'):
env = environ.get_dict(m=metadata)
interpreter = output.get('script_interpreter')
if not interpreter:
interpreter_and_args = guess_interpreter(output['script'])
interpreter_and_args[0] = external.find_executable(interpreter_and_args[0],
metadata.config.build_prefix)
if not interpreter_and_args[0]:
log.error("Did not find an interpreter to run {}, looked for {}".format(
output['script'], interpreter_and_args[0]))
else:
interpreter_and_args = interpreter.split(' ')
initial_files = utils.prefix_files(metadata.config.host_prefix)
env_output = env.copy()
env_output['TOP_PKG_NAME'] = env['PKG_NAME']
env_output['TOP_PKG_VERSION'] = env['PKG_VERSION']
env_output['PKG_VERSION'] = metadata.version()
env_output['PKG_NAME'] = metadata.get_value('package/name')
for var in utils.ensure_list(metadata.get_value('build/script_env')):
if var not in os.environ:
raise ValueError("env var '{}' specified in script_env, but is not set."
.format(var))
env_output[var] = os.environ[var]
dest_file = os.path.join(metadata.config.work_dir, output['script'])
recipe_dir = (metadata.path or
metadata.meta.get('extra', {}).get('parent_recipe', {}).get('path', ''))
utils.copy_into(os.path.join(recipe_dir, output['script']), dest_file)
if activate_script:
_write_activation_text(dest_file, metadata)
bundle_stats = {}
utils.check_call_env(interpreter_and_args + [dest_file],
cwd=metadata.config.work_dir, env=env_output, stats=bundle_stats)
log_stats(bundle_stats, "bundling {}".format(metadata.name()))
if stats is not None:
stats[stats_key(metadata, 'bundle_{}'.format(metadata.name()))] = bundle_stats
elif files:
# Files is specified by the output
# we exclude the list of files that we want to keep, so post-process picks them up as "new"
keep_files = set(os.path.normpath(pth)
for pth in utils.expand_globs(files, metadata.config.host_prefix))
pfx_files = set(utils.prefix_files(metadata.config.host_prefix))
initial_files = set(item for item in (pfx_files - keep_files)
if not any(keep_file.startswith(item + os.path.sep)
for keep_file in keep_files))
initial_files = set(item for item in (pfx_files - keep_files)
if not any(keep_file.startswith(item + os.path.sep)
for keep_file in keep_files))
else:
if not metadata.always_include_files():
log.warn("No files or script found for output {}".format(output.get('name')))
build_deps = metadata.get_value('requirements/build')
host_deps = metadata.get_value('requirements/host')
build_pkgs = [pkg.split()[0] for pkg in build_deps]
host_pkgs = [pkg.split()[0] for pkg in host_deps]
dangerous_double_deps = {'python': 'PYTHON', 'r-base': 'R'}
for dep, env_var_name in dangerous_double_deps.items():
if all(dep in pkgs_list for pkgs_list in (build_pkgs, host_pkgs)):
raise CondaBuildException("Empty package; {0} present in build and host deps. "
"You probably picked up the build environment's {0} "
" executable. You need to alter your recipe to "
" use the {1} env var in your recipe to "
"run that executable.".format(dep, env_var_name))
elif (dep in build_pkgs and metadata.uses_new_style_compiler_activation):
link = ("https://conda.io/docs/user-guide/tasks/build-packages/"
"define-metadata.html#host")
raise CondaBuildException("Empty package; {0} dep present in build but not "
"host requirements. You need to move your {0} dep "
"to the host requirements section. See {1} for more "
"info." .format(dep, link))
initial_files = set(utils.prefix_files(metadata.config.host_prefix))
for pat in metadata.always_include_files():
has_matches = False
for f in set(initial_files):
if fnmatch.fnmatch(f, pat):
print("Including in package existing file", f)
initial_files.remove(f)
has_matches = True
if not has_matches:
log.warn("Glob %s from always_include_files does not match any files", pat)
files = post_process_files(metadata, initial_files)
if output.get('name') and output.get('name') != 'conda':
assert 'bin/conda' not in files and 'Scripts/conda.exe' not in files, ("Bug in conda-build "
"has included conda binary in package. Please report this on the conda-build issue "
"tracker.")
# first filter is so that info_files does not pick up ignored files
files = utils.filter_files(files, prefix=metadata.config.host_prefix)
# this is also copying things like run_test.sh into info/recipe
with tmp_chdir(metadata.config.host_prefix):
output['checksums'] = create_info_files(metadata, files, prefix=metadata.config.host_prefix)
for ext in ('.py', '.r', '.pl', '.lua', '.sh', '.bat'):
test_dest_path = os.path.join(metadata.config.info_dir, 'test', 'run_test' + ext)
script = output.get('test', {}).get('script')
if script and script.endswith(ext):
utils.copy_into(os.path.join(metadata.config.work_dir, output['test']['script']),
test_dest_path, metadata.config.timeout,
locking=metadata.config.locking)
elif (os.path.isfile(test_dest_path) and metadata.meta.get('extra', {}).get('parent_recipe') and
not metadata.meta.get('test', {}).get("commands")):
# the test belongs to the parent recipe. Don't include it in subpackages.
utils.rm_rf(test_dest_path)
# here we add the info files into the prefix, so we want to re-collect the files list
prefix_files = set(utils.prefix_files(metadata.config.host_prefix))
files = utils.filter_files(prefix_files - initial_files, prefix=metadata.config.host_prefix)
basename = '-'.join([output['name'], metadata.version(), metadata.build_id()])
tmp_archives = []
final_outputs = []
with TemporaryDirectory() as tmp:
tmp_path = os.path.join(tmp, basename)
def order(f):
# we don't care about empty files so send them back via 100000
fsize = os.stat(join(metadata.config.host_prefix, f)).st_size or 100000
# info/* records will be False == 0, others will be 1.
info_order = int(os.path.dirname(f) != 'info')