-
Notifications
You must be signed in to change notification settings - Fork 423
/
index.py
1377 lines (1187 loc) · 61.2 KB
/
index.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
# -*- coding: utf-8 -*-
# Copyright (C) 2018 Anaconda, Inc
# SPDX-License-Identifier: Proprietary
from __future__ import absolute_import, division, print_function, unicode_literals
import bz2
from collections import OrderedDict
import copy
from datetime import datetime
import functools
import json
from numbers import Number
import os
from os.path import abspath, basename, getmtime, getsize, isdir, isfile, join, splitext, dirname
import subprocess
import sys
import time
from uuid import uuid4
# Lots of conda internals here. Should refactor to use exports.
from conda.common.compat import ensure_binary
import pytz
from jinja2 import Environment, PackageLoader
from tqdm import tqdm
import yaml
from yaml.constructor import ConstructorError
from yaml.parser import ParserError
from yaml.scanner import ScannerError
from yaml.reader import ReaderError
import fnmatch
from functools import partial
import logging
import conda_package_handling.api
from conda_package_handling.api import InvalidArchiveError
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import Executor
# BAD BAD BAD - conda internals
from conda.core.subdir_data import SubdirData
from conda.models.channel import Channel
from . import conda_interface, utils
from .conda_interface import MatchSpec, VersionOrder, human_bytes, context
from .conda_interface import CondaError, CondaHTTPError, get_index, url_path
from .conda_interface import TemporaryDirectory
from .conda_interface import Resolve
from .utils import glob, get_logger, FileNotFoundError, JSONDecodeError
# 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,)
# TODO: better to define this in conda; doing it here because we're implementing it in conda-build first
CONDA_TARBALL_EXTENSIONS = ('.conda', '.tar.bz2')
log = get_logger(__name__)
# use this for debugging, because ProcessPoolExecutor isn't pdb/ipdb friendly
class DummyExecutor(Executor):
def map(self, func, *iterables):
for iterable in iterables:
for thing in iterable:
yield func(thing)
try:
from conda.base.constants import NAMESPACES_MAP, NAMESPACE_PACKAGE_NAMES
except ImportError:
NAMESPACES_MAP = { # base package name, namespace
"python": "python",
"r": "r",
"r-base": "r",
"mro-base": "r",
"mro-base_impl": "r",
"erlang": "erlang",
"java": "java",
"openjdk": "java",
"julia": "julia",
"latex": "latex",
"lua": "lua",
"nodejs": "js",
"perl": "perl",
"php": "php",
"ruby": "ruby",
"m2-base": "m2",
"msys2-conda-epoch": "m2w64",
}
NAMESPACE_PACKAGE_NAMES = frozenset(NAMESPACES_MAP)
NAMESPACES = frozenset(NAMESPACES_MAP.values())
local_index_timestamp = 0
cached_index = None
local_subdir = ""
cached_channels = []
channel_data = {}
# TODO: support for libarchive seems to have broken ability to use multiple threads here.
# The new conda format is so much faster that it more than makes up for it. However, it
# would be nice to fix this at some point.
MAX_THREADS_DEFAULT = os.cpu_count() if (hasattr(os, "cpu_count") and os.cpu_count() > 1) else 1
if sys.platform == 'win32': # see https://github.com/python/cpython/commit/8ea0fd85bc67438f679491fae29dfe0a3961900a
MAX_THREADS_DEFAULT = min(48, MAX_THREADS_DEFAULT)
LOCK_TIMEOUT_SECS = 3 * 3600
LOCKFILE_NAME = ".lock"
# TODO: this is to make sure that the index doesn't leak tokens. It breaks use of private channels, though.
# os.environ['CONDA_ADD_ANACONDA_TOKEN'] = "false"
try:
from cytoolz.itertoolz import concat, concatv, groupby
except ImportError: # pragma: no cover
from conda._vendor.toolz.itertoolz import concat, concatv, groupby # NOQA
def get_build_index(subdir, bldpkgs_dir, output_folder=None, clear_cache=False,
omit_defaults=False, channel_urls=None, debug=False, verbose=True,
**kwargs):
global local_index_timestamp
global local_subdir
global cached_index
global cached_channels
global channel_data
mtime = 0
channel_urls = list(utils.ensure_list(channel_urls))
if not output_folder:
output_folder = dirname(bldpkgs_dir)
# check file modification time - this is the age of our local index.
index_file = os.path.join(output_folder, subdir, 'repodata.json')
if os.path.isfile(index_file):
mtime = os.path.getmtime(index_file)
if (clear_cache or
not os.path.isfile(index_file) or
local_subdir != subdir or
mtime > local_index_timestamp or
cached_channels != channel_urls):
# priority: (local as either croot or output_folder IF NOT EXPLICITLY IN CHANNEL ARGS),
# then channels passed as args (if local in this, it remains in same order),
# then channels from condarc.
urls = list(channel_urls)
loggers = utils.LoggingContext.default_loggers + [__name__]
if debug:
log_context = partial(utils.LoggingContext, logging.DEBUG, loggers=loggers)
elif verbose:
log_context = partial(utils.LoggingContext, logging.WARN, loggers=loggers)
else:
log_context = partial(utils.LoggingContext, logging.CRITICAL + 1, loggers=loggers)
with log_context():
# this is where we add the "local" channel. It's a little smarter than conda, because
# conda does not know about our output_folder when it is not the default setting.
if os.path.isdir(output_folder):
local_path = url_path(output_folder)
# replace local with the appropriate real channel. Order is maintained.
urls = [url if url != 'local' else local_path for url in urls]
if local_path not in urls:
urls.insert(0, local_path)
_ensure_valid_channel(output_folder, subdir)
update_index(output_folder, verbose=debug)
# replace noarch with native subdir - this ends up building an index with both the
# native content and the noarch content.
if subdir == 'noarch':
subdir = conda_interface.subdir
try:
cached_index = get_index(channel_urls=urls,
prepend=not omit_defaults,
use_local=False,
use_cache=context.offline,
platform=subdir)
# HACK: defaults does not have the many subfolders we support. Omit it and
# try again.
except CondaHTTPError:
if 'defaults' in urls:
urls.remove('defaults')
cached_index = get_index(channel_urls=urls,
prepend=omit_defaults,
use_local=False,
use_cache=context.offline,
platform=subdir)
expanded_channels = {rec.channel for rec in cached_index.values()}
superchannel = {}
# we need channeldata.json too, as it is a more reliable source of run_exports data
for channel in expanded_channels:
if channel.scheme == "file":
location = channel.location
if utils.on_win:
location = location.lstrip("/")
elif (not os.path.isabs(channel.location) and
os.path.exists(os.path.join(os.path.sep, channel.location))):
location = os.path.join(os.path.sep, channel.location)
channeldata_file = os.path.join(location, channel.name, 'channeldata.json')
retry = 0
max_retries = 1
if os.path.isfile(channeldata_file):
while retry < max_retries:
try:
with open(channeldata_file, "r+") as f:
channel_data[channel.name] = json.load(f)
break
except (IOError, JSONDecodeError):
time.sleep(0.2)
retry += 1
else:
# download channeldata.json for url
if not context.offline:
try:
channel_data[channel.name] = utils.download_channeldata(channel.base_url + '/channeldata.json')
except CondaHTTPError:
continue
# collapse defaults metachannel back into one superchannel, merging channeldata
if channel.base_url in context.default_channels and channel_data.get(channel.name):
packages = superchannel.get('packages', {})
packages.update(channel_data[channel.name])
superchannel['packages'] = packages
channel_data['defaults'] = superchannel
local_index_timestamp = os.path.getmtime(index_file)
local_subdir = subdir
cached_channels = channel_urls
return cached_index, local_index_timestamp, channel_data
def _ensure_valid_channel(local_folder, subdir):
for folder in {subdir, 'noarch'}:
path = os.path.join(local_folder, folder)
if not os.path.isdir(path):
os.makedirs(path)
def update_index(dir_path, check_md5=False, channel_name=None, patch_generator=None, threads=MAX_THREADS_DEFAULT,
verbose=False, progress=False, hotfix_source_repo=None, subdirs=None, warn=True,
current_index_versions=None, debug=False):
"""
If dir_path contains a directory named 'noarch', the path tree therein is treated
as though it's a full channel, with a level of subdirs, each subdir having an update
to repodata.json. The full channel will also have a channeldata.json file.
If dir_path does not contain a directory named 'noarch', but instead contains at least
one '*.tar.bz2' file, the directory is assumed to be a standard subdir, and only repodata.json
information will be updated.
"""
base_path, dirname = os.path.split(dir_path)
if dirname in utils.DEFAULT_SUBDIRS:
if warn:
log.warn("The update_index function has changed to index all subdirs at once. You're pointing it at a single subdir. "
"Please update your code to point it at the channel root, rather than a subdir.")
return update_index(base_path, check_md5=check_md5, channel_name=channel_name,
threads=threads, verbose=verbose, progress=progress,
hotfix_source_repo=hotfix_source_repo,
current_index_versions=current_index_versions)
return ChannelIndex(dir_path, channel_name, subdirs=subdirs, threads=threads,
deep_integrity_check=check_md5, debug=debug).index(
patch_generator=patch_generator, verbose=verbose,
progress=progress,
hotfix_source_repo=hotfix_source_repo,
current_index_versions=current_index_versions)
def _determine_namespace(info):
if info.get('namespace'):
namespace = info['namespace']
else:
depends_names = set()
for spec in info.get('depends', []):
try:
depends_names.add(MatchSpec(spec).name)
except CondaError:
pass
spaces = depends_names & NAMESPACE_PACKAGE_NAMES
if len(spaces) == 1:
namespace = NAMESPACES_MAP[spaces.pop()]
else:
namespace = "global"
info['namespace'] = namespace
if not info.get('namespace_in_name') and '-' in info['name']:
namespace_prefix, reduced_name = info['name'].split('-', 1)
if namespace_prefix == namespace:
info['name_in_channel'] = info['name']
info['name'] = reduced_name
return namespace, info.get('name_in_channel', info['name']), info['name']
def _make_seconds(timestamp):
timestamp = int(timestamp)
if timestamp > 253402300799: # 9999-12-31
timestamp //= 1000 # convert milliseconds to seconds; see conda/conda-build#1988
return timestamp
# ==========================================================================
REPODATA_VERSION = 1
CHANNELDATA_VERSION = 1
REPODATA_JSON_FN = 'repodata.json'
REPODATA_FROM_PKGS_JSON_FN = 'repodata_from_packages.json'
CHANNELDATA_FIELDS = (
"description",
"dev_url",
"doc_url",
"doc_source_url",
"home",
"license",
"reference_package",
"source_url",
"source_git_url",
"source_git_tag",
"source_git_rev",
"summary",
"version",
"subdirs",
"icon_url",
"icon_hash", # "md5:abc123:12"
"run_exports",
"binary_prefix",
"text_prefix",
"activate.d",
"deactivate.d",
"pre_link",
"post_link",
"pre_unlink",
"tags",
"identifiers",
"keywords",
"recipe_origin",
"commits",
)
def _clear_newline_chars(record, field_name):
if field_name in record:
try:
record[field_name] = record[field_name].strip().replace('\n', ' ')
except AttributeError:
# sometimes description gets added as a list instead of just a string
record[field_name] = record[field_name][0].strip().replace('\n', ' ')
def _apply_instructions(subdir, repodata, instructions):
repodata.setdefault("removed", [])
utils.merge_or_update_dict(repodata.get('packages', {}), instructions.get('packages', {}), merge=False,
add_missing_keys=False)
# we could have totally separate instructions for .conda than .tar.bz2, but it's easier if we assume
# that a similarly-named .tar.bz2 file is the same content as .conda, and shares fixes
new_pkg_fixes = {k.replace('.tar.bz2', '.conda'): v for k, v in instructions.get('packages', {}).items()}
utils.merge_or_update_dict(repodata.get('packages.conda', {}), new_pkg_fixes, merge=False,
add_missing_keys=False)
utils.merge_or_update_dict(repodata.get('packages.conda', {}), instructions.get('packages.conda', {}), merge=False,
add_missing_keys=False)
for fn in instructions.get('revoke', ()):
for key in ('packages', 'packages.conda'):
if fn.endswith('.tar.bz2') and key == 'packages.conda':
fn = fn.replace('.tar.bz2', '.conda')
if fn in repodata[key]:
repodata[key][fn]['revoked'] = True
repodata[key][fn]['depends'].append('package_has_been_revoked')
for fn in instructions.get('remove', ()):
for key in ('packages', 'packages.conda'):
if fn.endswith('.tar.bz2') and key == 'packages.conda':
fn = fn.replace('.tar.bz2', '.conda')
popped = repodata[key].pop(fn, None)
if popped:
repodata["removed"].append(fn)
repodata["removed"].sort()
return repodata
def _get_jinja2_environment():
def _filter_strftime(dt, dt_format):
if isinstance(dt, Number):
if dt > 253402300799: # 9999-12-31
dt //= 1000 # convert milliseconds to seconds; see #1988
dt = datetime.utcfromtimestamp(dt).replace(tzinfo=pytz.timezone("UTC"))
return dt.strftime(dt_format)
def _filter_add_href(text, link, **kwargs):
if link:
kwargs_list = ['href="{0}"'.format(link)]
kwargs_list.append('alt="{0}"'.format(text))
kwargs_list += ['{0}="{1}"'.format(k, v) for k, v in kwargs.items()]
return '<a {0}>{1}</a>'.format(' '.join(kwargs_list), text)
else:
return text
environment = Environment(
loader=PackageLoader('conda_build', 'templates'),
)
environment.filters['human_bytes'] = human_bytes
environment.filters['strftime'] = _filter_strftime
environment.filters['add_href'] = _filter_add_href
environment.trim_blocks = True
environment.lstrip_blocks = True
return environment
def _maybe_write(path, content, write_newline_end=False, content_is_binary=False):
# Create the temp file next "path" so that we can use an atomic move, see
# https://github.com/conda/conda-build/issues/3833
temp_path = '%s.%s' % (path, uuid4())
if not content_is_binary:
content = ensure_binary(content)
with open(temp_path, 'wb') as fh:
fh.write(content)
if write_newline_end:
fh.write(b'\n')
if isfile(path):
if utils.md5_file(temp_path) == utils.md5_file(path):
# No need to change mtimes. The contents already match.
os.unlink(temp_path)
return False
# log.info("writing %s", path)
utils.move_with_fallback(temp_path, path)
return True
def _make_build_string(build, build_number):
build_number_as_string = str(build_number)
if build.endswith(build_number_as_string):
build = build[:-len(build_number_as_string)]
build = build.rstrip("_")
build_string = build
return build_string
def _warn_on_missing_dependencies(missing_dependencies, patched_repodata):
"""
The following dependencies do not exist in the channel and are not declared
as external dependencies:
dependency1:
- subdir/fn1.tar.bz2
- subdir/fn2.tar.bz2
dependency2:
- subdir/fn3.tar.bz2
- subdir/fn4.tar.bz2
The associated packages are being removed from the index.
"""
if missing_dependencies:
builder = [
"WARNING: The following dependencies do not exist in the channel",
" and are not declared as external dependencies:"
]
for dep_name in sorted(missing_dependencies):
builder.append(" %s" % dep_name)
for subdir_fn in sorted(missing_dependencies[dep_name]):
builder.append(" - %s" % subdir_fn)
subdir, fn = subdir_fn.split("/")
popped = patched_repodata["packages"].pop(fn, None)
if popped:
patched_repodata["removed"].append(fn)
builder.append("The associated packages are being removed from the index.")
builder.append('')
log.warn("\n".join(builder))
def _cache_post_install_details(paths_cache_path, post_install_cache_path):
post_install_details_json = {'binary_prefix': False, 'text_prefix': False,
'activate.d': False, 'deactivate.d': False,
'pre_link': False, 'post_link': False, 'pre_unlink': False}
if os.path.lexists(paths_cache_path):
with open(paths_cache_path) as f:
paths = json.load(f).get('paths', [])
# get embedded prefix data from paths.json
for f in paths:
if f.get('prefix_placeholder'):
if f.get('file_mode') == 'binary':
post_install_details_json['binary_prefix'] = True
elif f.get('file_mode') == 'text':
post_install_details_json['text_prefix'] = True
# check for any activate.d/deactivate.d scripts
for k in ('activate.d', 'deactivate.d'):
if not post_install_details_json.get(k) and f['_path'].startswith('etc/conda/%s' % k):
post_install_details_json[k] = True
# check for any link scripts
for pat in ('pre-link', 'post-link', 'pre-unlink'):
if not post_install_details_json.get(pat) and fnmatch.fnmatch(f['_path'], '*/.*-%s.*' % pat):
post_install_details_json[pat.replace("-", "_")] = True
with open(post_install_cache_path, 'w') as fh:
json.dump(post_install_details_json, fh)
def _cache_recipe(tmpdir, recipe_cache_path):
recipe_path_search_order = (
'info/recipe/meta.yaml.rendered',
'info/recipe/meta.yaml',
'info/meta.yaml',
)
for path in recipe_path_search_order:
recipe_path = os.path.join(tmpdir, path)
if os.path.lexists(recipe_path):
break
recipe_path = None
recipe_json = {}
if recipe_path:
with open(recipe_path) as f:
try:
recipe_json = yaml.safe_load(f)
except (ConstructorError, ParserError, ScannerError, ReaderError):
pass
try:
recipe_json_str = json.dumps(recipe_json)
except TypeError:
recipe_json.get('requirements', {}).pop('build')
recipe_json_str = json.dumps(recipe_json)
with open(recipe_cache_path, 'w') as fh:
fh.write(recipe_json_str)
return recipe_json
def _cache_run_exports(tmpdir, run_exports_cache_path):
run_exports = {}
try:
with open(os.path.join(tmpdir, 'info', 'run_exports.json')) as f:
run_exports = json.load(f)
except (IOError, FileNotFoundError):
try:
with open(os.path.join(tmpdir, 'info', 'run_exports.yaml')) as f:
run_exports = yaml.safe_load(f)
except (IOError, FileNotFoundError):
log.debug("%s has no run_exports file (this is OK)" % tmpdir)
with open(run_exports_cache_path, 'w') as fh:
json.dump(run_exports, fh)
def _cache_icon(tmpdir, recipe_json, icon_cache_path):
# If a conda package contains an icon, also extract and cache that in an .icon/
# directory. The icon file name is the name of the package, plus the extension
# of the icon file as indicated by the meta.yaml `app/icon` key.
# apparently right now conda-build renames all icons to 'icon.png'
# What happens if it's an ico file, or a svg file, instead of a png? Not sure!
app_icon_path = recipe_json.get('app', {}).get('icon')
if app_icon_path:
icon_path = os.path.join(tmpdir, 'info', 'recipe', app_icon_path)
if not os.path.lexists(icon_path):
icon_path = os.path.join(tmpdir, 'info', 'icon.png')
if os.path.lexists(icon_path):
icon_cache_path += splitext(app_icon_path)[-1]
utils.move_with_fallback(icon_path, icon_cache_path)
def _make_subdir_index_html(channel_name, subdir, repodata_packages, extra_paths):
environment = _get_jinja2_environment()
template = environment.get_template('subdir-index.html.j2')
rendered_html = template.render(
title="%s/%s" % (channel_name or '', subdir),
packages=repodata_packages,
current_time=datetime.utcnow().replace(tzinfo=pytz.timezone("UTC")),
extra_paths=extra_paths,
)
return rendered_html
def _make_channeldata_index_html(channel_name, channeldata):
environment = _get_jinja2_environment()
template = environment.get_template('channeldata-index.html.j2')
rendered_html = template.render(
title=channel_name,
packages=channeldata['packages'],
subdirs=channeldata['subdirs'],
current_time=datetime.utcnow().replace(tzinfo=pytz.timezone("UTC")),
)
return rendered_html
def _get_source_repo_git_info(path):
is_repo = subprocess.check_output(["git", "rev-parse", "--is-inside-work-tree"], cwd=path)
if is_repo.strip().decode('utf-8') == "true":
output = subprocess.check_output(['git', 'log',
"--pretty=format:'%h|%ad|%an|%s'",
"--date=unix"], cwd=path)
commits = []
for line in output.decode("utf-8").strip().splitlines():
_hash, _time, _author, _desc = line.split("|")
commits.append({"hash": _hash, "timestamp": int(_time),
"author": _author, "description": _desc})
return commits
def _cache_info_file(tmpdir, info_fn, cache_path):
info_path = os.path.join(tmpdir, 'info', info_fn)
if os.path.lexists(info_path):
utils.move_with_fallback(info_path, cache_path)
def _alternate_file_extension(fn):
cache_fn = fn
for ext in CONDA_TARBALL_EXTENSIONS:
cache_fn = cache_fn.replace(ext, '')
other_ext = set(CONDA_TARBALL_EXTENSIONS) - set([fn.replace(cache_fn, '')])
return cache_fn + next(iter(other_ext))
def _get_resolve_object(subdir, file_path=None, precs=None, repodata=None):
packages = {}
conda_packages = {}
if file_path:
with open(file_path) as fi:
packages = json.load(fi)
recs = json.load(fi)
for k, v in recs.items():
if k.endswith('.tar.bz2'):
packages[k] = v
elif k.endswith('.conda'):
conda_packages[k] = v
if not repodata:
repodata = {
"info": {
"subdir": subdir,
"arch": context.arch_name,
"platform": context.platform,
},
"packages": packages,
"packages.conda": conda_packages,
}
channel = Channel('https://conda.anaconda.org/dummy-channel/%s' % subdir)
sd = SubdirData(channel)
sd._process_raw_repodata_str(json.dumps(repodata))
sd._loaded = True
SubdirData._cache_[channel.url(with_credentials=True)] = sd
index = {prec: prec for prec in precs or sd._package_records}
r = Resolve(index, channels=(channel,))
return r
def _get_newest_versions(r, pins={}):
groups = {}
for g_name, g_recs in r.groups.items():
if g_name in pins:
matches = []
for pin in pins[g_name]:
version = r.find_matches(MatchSpec('%s=%s' % (g_name, pin)))[0].version
matches.extend(r.find_matches(MatchSpec('%s=%s' % (g_name, version))))
else:
version = r.groups[g_name][0].version
matches = r.find_matches(MatchSpec('%s=%s' % (g_name, version)))
groups[g_name] = matches
return [pkg for group in groups.values() for pkg in group]
def _add_missing_deps(new_r, original_r):
"""For each package in new_r, if any deps are not satisfiable, backfill them from original_r."""
expanded_groups = copy.deepcopy(new_r.groups)
seen_specs = set()
for g_name, g_recs in new_r.groups.items():
for g_rec in g_recs:
for dep_spec in g_rec.depends:
if dep_spec in seen_specs:
continue
ms = MatchSpec(dep_spec)
if not new_r.find_matches(ms):
matches = original_r.find_matches(ms)
if matches:
version = matches[0].version
expanded_groups[ms.name] = (
set(expanded_groups.get(ms.name, [])) |
set(original_r.find_matches(MatchSpec('%s=%s' % (ms.name, version)))))
seen_specs.add(dep_spec)
return [pkg for group in expanded_groups.values() for pkg in group]
def _shard_newest_packages(subdir, r, pins=None):
"""Captures only the newest versions of software in the resolve object.
For things where more than one version is supported simultaneously (like Python),
pass pins as a dictionary, with the key being the package name, and the value being
a list of supported versions. For example:
{'python': ["2.7", "3.6"]}
"""
groups = {}
pins = pins or {}
for g_name, g_recs in r.groups.items():
# always do the latest implicitly
version = r.groups[g_name][0].version
matches = set(r.find_matches(MatchSpec('%s=%s' % (g_name, version))))
if g_name in pins:
for pin_value in pins[g_name]:
version = r.find_matches(MatchSpec('%s=%s' % (g_name, pin_value)))[0].version
matches.update(r.find_matches(MatchSpec('%s=%s' % (g_name, version))))
groups[g_name] = matches
new_r = _get_resolve_object(subdir, precs=[pkg for group in groups.values() for pkg in group])
return set(_add_missing_deps(new_r, r))
def _build_current_repodata(subdir, repodata, pins):
r = _get_resolve_object(subdir, repodata=repodata)
keep_pkgs = _shard_newest_packages(subdir, r, pins)
new_repodata = {k: repodata[k] for k in set(repodata.keys()) - set(['packages', 'packages.conda'])}
packages = {}
conda_packages = {}
for keep_pkg in keep_pkgs:
if keep_pkg.fn.endswith('.conda'):
conda_packages[keep_pkg.fn] = repodata['packages.conda'][keep_pkg.fn]
# in order to prevent package churn we consider the md5 for the .tar.bz2 that matches the .conda file
# This holds when .conda files contain the same files as .tar.bz2, which is an assumption we'll make
# until it becomes more prevalent that people provide only .conda files and just skip .tar.bz2
counterpart = keep_pkg.fn.replace('.conda', '.tar.bz2')
conda_packages[keep_pkg.fn]['legacy_bz2_md5'] = repodata['packages'].get(counterpart, {}).get('md5')
elif keep_pkg.fn.endswith('.tar.bz2'):
packages[keep_pkg.fn] = repodata['packages'][keep_pkg.fn]
new_repodata['packages'] = packages
new_repodata['packages.conda'] = conda_packages
return new_repodata
class ChannelIndex(object):
def __init__(self, channel_root, channel_name, subdirs=None, threads=MAX_THREADS_DEFAULT,
deep_integrity_check=False, debug=False):
self.channel_root = abspath(channel_root)
self.channel_name = channel_name or basename(channel_root.rstrip('/'))
self._subdirs = subdirs
self.thread_executor = (DummyExecutor()
if(debug or sys.version_info.major == 2 or threads == 1)
else ProcessPoolExecutor(threads))
self.deep_integrity_check = deep_integrity_check
def index(self, patch_generator, hotfix_source_repo=None, verbose=False, progress=False,
current_index_versions=None):
if verbose:
level = logging.DEBUG
else:
level = logging.ERROR
with utils.LoggingContext(level, loggers=[__name__]):
if not self._subdirs:
detected_subdirs = set(subdir for subdir in os.listdir(self.channel_root)
if subdir in utils.DEFAULT_SUBDIRS and isdir(join(self.channel_root, subdir)))
log.debug("found subdirs %s" % detected_subdirs)
self.subdirs = subdirs = sorted(detected_subdirs | {'noarch'})
else:
self.subdirs = subdirs = sorted(set(self._subdirs) | {'noarch'})
# Step 1. Lock local channel.
with utils.try_acquire_locks([utils.get_lock(self.channel_root)], timeout=900):
channel_data = {}
channeldata_file = os.path.join(self.channel_root, 'channeldata.json')
if os.path.isfile(channeldata_file):
with open(channeldata_file) as f:
channel_data = json.load(f)
# Step 2. Collect repodata from packages, save to pkg_repodata.json file
with tqdm(total=len(subdirs), disable=(verbose or not progress), leave=False) as t:
for subdir in subdirs:
t.set_description("Subdir: %s" % subdir)
t.update()
with tqdm(total=8, disable=(verbose or not progress), leave=False) as t2:
t2.set_description("Gathering repodata")
t2.update()
_ensure_valid_channel(self.channel_root, subdir)
repodata_from_packages = self.index_subdir(
subdir, verbose=verbose, progress=progress)
t2.set_description("Writing pre-patch repodata")
t2.update()
self._write_repodata(subdir, repodata_from_packages,
REPODATA_FROM_PKGS_JSON_FN)
# Step 3. Apply patch instructions.
t2.set_description("Applying patch instructions")
t2.update()
patched_repodata, patch_instructions = self._patch_repodata(
subdir, repodata_from_packages, patch_generator)
# Step 4. Save patched and augmented repodata.
# If the contents of repodata have changed, write a new repodata.json file.
# Also create associated index.html.
t2.set_description("Writing patched repodata")
t2.update()
self._write_repodata(subdir, patched_repodata, REPODATA_JSON_FN)
t2.set_description("Building current_repodata subset")
t2.update()
current_repodata = _build_current_repodata(subdir, patched_repodata,
pins=current_index_versions)
t2.set_description("Writing current_repodata subset")
t2.update()
self._write_repodata(subdir, current_repodata, json_filename="current_repodata.json")
t2.set_description("Writing subdir index HTML")
t2.update()
self._write_subdir_index_html(subdir, patched_repodata)
t2.set_description("Updating channeldata")
t2.update()
self._update_channeldata(channel_data, patched_repodata, subdir)
# Step 7. Create and write channeldata.
self._write_channeldata_index_html(channel_data)
self._write_channeldata(channel_data)
def index_subdir(self, subdir, verbose=False, progress=False):
subdir_path = join(self.channel_root, subdir)
self._ensure_dirs(subdir)
repodata_json_path = join(subdir_path, REPODATA_FROM_PKGS_JSON_FN)
if verbose:
log.info("Building repodata for %s" % subdir_path)
# gather conda package filenames in subdir
# we'll process these first, because reading their metadata is much faster
fns_in_subdir = {fn for fn in os.listdir(subdir_path) if fn.endswith('.conda') or fn.endswith('.tar.bz2')}
# load current/old repodata
try:
with open(repodata_json_path) as fh:
old_repodata = json.load(fh) or {}
except (EnvironmentError, JSONDecodeError):
# log.info("no repodata found at %s", repodata_json_path)
old_repodata = {}
old_repodata_packages = old_repodata.get("packages", {})
old_repodata_conda_packages = old_repodata.get("packages.conda", {})
old_repodata_fns = set(old_repodata_packages) | set(old_repodata_conda_packages)
# Load stat cache. The stat cache has the form
# {
# 'package_name.tar.bz2': {
# 'mtime': 123456,
# 'md5': 'abd123',
# },
# }
stat_cache_path = join(subdir_path, '.cache', 'stat.json')
try:
with open(stat_cache_path) as fh:
stat_cache = json.load(fh) or {}
except:
stat_cache = {}
stat_cache_original = stat_cache.copy()
try:
# calculate all the paths and figure out what we're going to do with them
# add_set: filenames that aren't in the current/old repodata, but exist in the subdir
add_set = fns_in_subdir - old_repodata_fns
remove_set = old_repodata_fns - fns_in_subdir
ignore_set = set(old_repodata.get('removed', []))
add_set -= ignore_set
# update_set: Filenames that are in both old repodata and new repodata,
# and whose contents have changed based on file size or mtime. We're
# not using md5 here because it takes too long. If needing to do full md5 checks,
# use the --deep-integrity-check flag / self.deep_integrity_check option.
update_set = self._calculate_update_set(
subdir, fns_in_subdir, old_repodata_fns, stat_cache,
verbose=verbose, progress=progress
)
# unchanged_set: packages in old repodata whose information can carry straight
# across to new repodata
unchanged_set = sorted(old_repodata_fns - update_set - remove_set - ignore_set)
# clean up removed files
removed_set = (old_repodata_fns - fns_in_subdir)
for fn in removed_set:
if fn in stat_cache:
del stat_cache[fn]
new_repodata_packages = {k: v for k, v in old_repodata.get('packages', {}).items() if k in unchanged_set}
new_repodata_conda_packages = {k: v for k, v in old_repodata.get('packages.conda', {}).items() if k in unchanged_set}
for k in unchanged_set:
if not (k in new_repodata_packages or k in new_repodata_conda_packages):
fn, rec = ChannelIndex._load_index_from_cache(self.channel_root, subdir, fn, stat_cache)
# this is how we pass an exception through. When fn == rec, there's been a problem,
# and we need to reload this file
if fn == rec:
update_set.add(fn)
else:
if fn.endswith('.tar.bz2'):
new_repodata_packages[fn] = rec
else:
new_repodata_conda_packages[fn] = rec
# Invalidate cached files for update_set.
# Extract and cache update_set and add_set, then add to new_repodata_packages.
# This is also where we update the contents of the stat_cache for successfully
# extracted packages.
# Sorting here prioritizes .conda files ('c') over .tar.bz2 files ('b')
hash_extract_set = tuple(concatv(add_set, update_set))
extract_func = functools.partial(ChannelIndex._extract_to_cache,
self.channel_root, subdir)
# split up the set by .conda packages first, then .tar.bz2. This avoids race conditions
# with execution in parallel that would end up in the same place.
for conda_format in tqdm(CONDA_TARBALL_EXTENSIONS, desc="File format",
disable=(verbose or not progress), leave=False):
for fn, mtime, size, index_json in tqdm(
self.thread_executor.map(
extract_func,
(fn for fn in hash_extract_set if fn.endswith(conda_format))),
desc="hash & extract packages for %s" % subdir,
disable=(verbose or not progress), leave=False):
# fn can be None if the file was corrupt or no longer there
if fn and mtime:
stat_cache[fn] = {'mtime': int(mtime), 'size': size}
if index_json:
if fn.endswith(".conda"):
new_repodata_conda_packages[fn] = index_json
else:
new_repodata_packages[fn] = index_json
else:
log.error("Package at %s did not contain valid index.json data. Please"
" check the file and remove/redownload if necessary to obtain "
"a valid package." % os.path.join(subdir_path, fn))
new_repodata = {
'packages': new_repodata_packages,
'packages.conda': new_repodata_conda_packages,
'info': {
'subdir': subdir,
},
'repodata_version': REPODATA_VERSION,
'removed': sorted(list(ignore_set))
}
finally:
if stat_cache != stat_cache_original:
# log.info("writing stat cache to %s", stat_cache_path)
with open(stat_cache_path, 'w') as fh:
json.dump(stat_cache, fh)
return new_repodata
def _ensure_dirs(self, subdir):
# Create all cache directories in the subdir.
ensure = lambda path: isdir(path) or os.makedirs(path)
cache_path = join(self.channel_root, subdir, '.cache')
ensure(cache_path)
ensure(join(cache_path, 'index'))
ensure(join(cache_path, 'about'))
ensure(join(cache_path, 'paths'))
ensure(join(cache_path, 'recipe'))
ensure(join(cache_path, 'run_exports'))
ensure(join(cache_path, 'post_install'))
ensure(join(cache_path, 'icon'))
ensure(join(self.channel_root, 'icons'))
ensure(join(cache_path, 'recipe_log'))
def _calculate_update_set(self, subdir, fns_in_subdir, old_repodata_fns, stat_cache,
verbose=False, progress=True):
# Determine the packages that already exist in repodata, but need to be updated.
# We're not using md5 here because it takes too long.
candidate_fns = fns_in_subdir & old_repodata_fns
subdir_path = join(self.channel_root, subdir)
update_set = set()
for fn in tqdm(iter(candidate_fns), desc="Finding updated files",
disable=(verbose or not progress), leave=False):
if fn not in stat_cache:
update_set.add(fn)
else:
stat_result = os.stat(join(subdir_path, fn))
if (int(stat_result.st_mtime) != int(stat_cache[fn]['mtime']) or
stat_result.st_size != stat_cache[fn]['size']):
update_set.add(fn)
return update_set
@staticmethod
def _extract_to_cache(channel_root, subdir, fn, second_try=False):
# This method WILL reread the tarball. Probably need another one to exit early if
# there are cases where it's fine not to reread. Like if we just rebuild repodata
# from the cached files, but don't use the existing repodata.json as a starting point.
subdir_path = join(channel_root, subdir)
# allow .conda files to reuse cache from .tar.bz2 and vice-versa.
# Assumes that .tar.bz2 and .conda files have exactly the same
# contents. This is convention, but not guaranteed, nor checked.
alternate_cache_fn = _alternate_file_extension(fn)