forked from conda/conda-build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cran.py
executable file
·1815 lines (1618 loc) · 65.8 KB
/
cran.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
# Copyright (C) 2014 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
Tools for converting Cran packages to conda recipes.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import re
import subprocess
import sys
import tarfile
import unicodedata
import zipfile
from itertools import chain
from os import environ, listdir, makedirs, sep
from os.path import (
basename,
commonprefix,
exists,
isabs,
isdir,
isfile,
join,
normpath,
realpath,
relpath,
)
import requests
import yaml
# try to import C dumper
try:
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import SafeDumper
from typing import TYPE_CHECKING
from conda.base.context import context
from conda.common.io import dashlist
from conda.gateways.disk.create import TemporaryDirectory
from .. import source
from ..config import get_or_merge_config
from ..license_family import allowed_license_families, guess_license_family
from ..metadata import MetaData
from ..utils import ensure_list, rm_rf
from ..variants import DEFAULT_VARIANTS, get_package_variants
if TYPE_CHECKING:
from typing import Literal
from ..config import Config
SOURCE_META = """\
{archive_keys}
{git_url_key} {git_url}
{git_tag_key} {git_tag}
{patches}
"""
BINARY_META = """\
url: {cranurl}{sel}
{hash_entry}{sel}
"""
VERSION_META = """\
{{% set version = '{cran_version}' %}}{sel}"""
CRAN_META = """\
{version_source}
{version_binary1}
{version_binary2}
{{% set posix = 'm2-' if win else '' %}}
{{% set native = 'm2w64-' if win else '' %}}
package:
name: {packagename}
version: {{{{ version|replace("-", "_") }}}}
source:
{source}
{binary1}
{binary2}
build:
merge_build_host: True{sel_src_and_win}
# If this is a new build for the same version, increment the build number.
number: {build_number}
{skip_os}
{noarch_generic}
# This is required to make R link correctly on Linux.
rpaths:
- lib/R/lib/
- lib/
{script_env}
{suggests}
requirements:
build:{build_depends}
host:{host_depends}
run:{run_depends}
test:
commands:
# You can put additional test commands to be run here.
- $R -e "library('{cran_packagename}')" # [not win]
- "\\"%R%\\" -e \\"library('{cran_packagename}')\\"" # [win]
# You can also put a file called run_test.py, run_test.sh, or run_test.bat
# in the recipe that will be run at test time.
# requires:
# Put any additional test requirements here.
about:
{home_comment}home:{homeurl}
license: {license}
{summary_comment}summary:{summary}
license_family: {license_family}
{license_file}
{extra_recipe_maintainers}
# The original CRAN metadata for this package was:
{cran_metadata}
# See
# https://docs.conda.io/projects/conda-build for
# more information about meta.yaml
"""
CRAN_BUILD_SH_SOURCE = """\
#!/bin/bash
# 'Autobrew' is being used by more and more packages these days
# to grab static libraries from Homebrew bottles. These bottles
# are fetched via Homebrew's --force-bottle option which grabs
# a bottle for the build machine which may not be macOS 10.9.
# Also, we want to use conda packages (and shared libraries) for
# these 'system' dependencies. See:
# https://github.com/jeroen/autobrew/issues/3
export DISABLE_AUTOBREW=1
# R refuses to build packages that mark themselves as Priority: Recommended
mv DESCRIPTION DESCRIPTION.old
grep -va '^Priority: ' DESCRIPTION.old > DESCRIPTION
# shellcheck disable=SC2086
${{R}} CMD INSTALL --build . ${{R_ARGS}}
# Add more build steps here, if they are necessary.
# See
# https://docs.conda.io/projects/conda-build
# for a list of environment variables that are set during the build process.
"""
CRAN_BUILD_SH_MIXED = """\
#!/bin/bash
set -o errexit -o pipefail
if {source_pf_bash}; then
export DISABLE_AUTOBREW=1
mv DESCRIPTION DESCRIPTION.old
grep -va '^Priority: ' DESCRIPTION.old > DESCRIPTION
# shellcheck disable=SC2086
${{R}} CMD INSTALL --build . ${{R_ARGS}}
else
mkdir -p "${{PREFIX}}"/lib/R/library/{cran_packagename}
mv ./* "${{PREFIX}}"/lib/R/library/{cran_packagename}
if [[ ${{target_platform}} == osx-64 ]]; then
pushd "${{PREFIX}}"
for libdir in lib/R/lib lib/R/modules lib/R/library lib/R/bin/exec sysroot/usr/lib; do
pushd "${{libdir}}" || exit 1
while IFS= read -r -d '' SHARED_LIB
do
echo "fixing SHARED_LIB ${{SHARED_LIB}}"
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5.0-MRO/Resources/lib/libR.dylib "${{PREFIX}}"/lib/R/lib/libR.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib "${{PREFIX}}"/lib/R/lib/libR.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/local/clang4/lib/libomp.dylib "${{PREFIX}}"/lib/libomp.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/local/gfortran/lib/libgfortran.3.dylib "${{PREFIX}}"/lib/libgfortran.3.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libquadmath.0.dylib "${{PREFIX}}"/lib/libquadmath.0.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/local/gfortran/lib/libquadmath.0.dylib "${{PREFIX}}"/lib/libquadmath.0.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libgfortran.3.dylib "${{PREFIX}}"/lib/libgfortran.3.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libgcc_s.1.dylib "${{PREFIX}}"/lib/libgcc_s.1.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libiconv.2.dylib "${{PREFIX}}"/sysroot/usr/lib/libiconv.2.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libncurses.5.4.dylib "${{PREFIX}}"/sysroot/usr/lib/libncurses.5.4.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libicucore.A.dylib "${{PREFIX}}"/sysroot/usr/lib/libicucore.A.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libexpat.1.dylib "${{PREFIX}}"/lib/libexpat.1.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libcurl.4.dylib "${{PREFIX}}"/lib/libcurl.4.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /usr/lib/libc++.1.dylib "${{PREFIX}}"/lib/libc++.1.dylib "${{SHARED_LIB}}" || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libc++.1.dylib "${{PREFIX}}"/lib/libc++.1.dylib "${{SHARED_LIB}}" || true
done < <(find . \\( -type f -iname "*.dylib" -or -iname "*.so" -or -iname "R" \\) -print0)
popd
done
popd
fi
fi
""" # noqa: E501
CRAN_BUILD_SH_BINARY = """\
#!/bin/bash
set -o errexit -o pipefail
mkdir -p "${{PREFIX}}"/lib/R/library/{cran_packagename}
mv ./* "${{PREFIX}}"/lib/R/library/{cran_packagename}
"""
CRAN_BLD_BAT_SOURCE = """\
"%R%" CMD INSTALL --build . %R_ARGS%
IF %ERRORLEVEL% NEQ 0 exit /B 1
"""
# We hardcode the fact that CRAN does not provide win32 binaries here.
CRAN_BLD_BAT_MIXED = """\
if "%target_platform%" == "win-64" goto skip_source_build
"%R%" CMD INSTALL --build . %R_ARGS%
IF %ERRORLEVEL% NEQ 0 exit /B 1
exit 0
:skip_source_build
mkdir %PREFIX%\\lib\\R\\library
robocopy /E . "%PREFIX%\\lib\\R\\library\\{cran_packagename}"
if %ERRORLEVEL% NEQ 1 exit /B 1
exit 0
"""
INDENT = "\n - "
CRAN_KEYS = [
"Site",
"Archs",
"Depends",
"Enhances",
"Imports",
"License",
"License_is_FOSS",
"License_restricts_use",
"LinkingTo",
"MD5sum",
"NeedsCompilation",
"OS_type",
"Package",
"Path",
"Priority",
"Suggests",
"Version",
"Title",
"Author",
"Maintainer",
]
# The following base/recommended package names are derived from R's source
# tree (R-3.0.2/share/make/vars.mk). Hopefully they don't change too much
# between versions.
R_BASE_PACKAGE_NAMES = (
"base",
"compiler",
"datasets",
"graphics",
"grDevices",
"grid",
"methods",
"parallel",
"splines",
"stats",
"stats4",
"tcltk",
"tools",
"utils",
)
R_RECOMMENDED_PACKAGE_NAMES = (
"MASS",
"lattice",
"Matrix",
"nlme",
"survival",
"boot",
"cluster",
"codetools",
"foreign",
"KernSmooth",
"rpart",
"class",
"nnet",
"spatial",
"mgcv",
)
# Stolen then tweaked from debian.deb822.PkgRelation.__dep_RE.
VERSION_DEPENDENCY_REGEX = re.compile(
r"^\s*(?P<name>[a-zA-Z0-9.+\-]{1,})"
r"(\s*\(\s*(?P<relop>[>=<]+)\s*"
r"(?P<version>[0-9a-zA-Z:\-+~.]+)\s*\))"
r"?(\s*\[(?P<archs>[\s!\w\-]+)\])?\s*$"
)
target_platform_bash_test_by_sel = {
"linux": "=~ linux.*",
"linux32": "== linux-32",
"linux64": "== linux-64",
"win32": "== win-32",
"win64": "== win-64",
"osx": "== osx-64",
}
def package_exists(package_name):
# TODO: how can we get cran to spit out package presence?
# available.packages() is probably a start, but no channels are working on mac right now?
return True
# install_output = subprocess.check_output([join(sys.prefix, "r"), "-e",
# # ind=2 arbitrarily chooses some CRAN mirror to try.
# "chooseCRANmirror(ind=2);install.packages('{}')".format(package_name)])
def add_parser(repos):
# for loading default variant info
cran = repos.add_parser(
"cran",
help="""
Create recipe skeleton for packages hosted on the Comprehensive R Archive
Network (CRAN) (cran.r-project.org).
""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
cran.add_argument(
"packages",
nargs="+",
help="""CRAN packages to create recipe skeletons for.""",
)
cran.add_argument(
"--output-dir",
help="Directory to write recipes to (default: %(default)s).",
default=".",
)
cran.add_argument(
"--output-suffix",
help="Suffix to add to recipe dir, can contain other dirs (eg: -feedstock/recipe).",
default="",
)
cran.add_argument(
"--add-maintainer",
help="Add this github username as a maintainer if not already present.",
)
cran.add_argument(
"--version",
help="Version to use. Applies to all packages.",
)
cran.add_argument(
"--git-tag",
help="Git tag to use for GitHub recipes.",
)
cran.add_argument(
"--all-urls",
action="store_true",
help="""Look at all URLs, not just source URLs. Use this if it can't
find the right URL.""",
)
cran.add_argument(
"--cran-url",
help="URL to use for as source package repository",
)
cran.add_argument(
"--r-interp",
default="r-base",
help="Declare R interpreter package",
)
cran.add_argument(
"--use-binaries-ver",
help=(
"Repackage binaries from version provided by argument instead of building "
"from source."
),
)
cran.add_argument(
"--use-when-no-binary",
choices=("src", "old", "src-old", "old-src", "error"),
default="src",
help="""Sometimes binaries are not available at the correct version for
a given platform (macOS). You can use this flag to specify what
fallback to take, either compiling from source or using an older
binary or trying one then the other.""",
)
cran.add_argument(
"--use-noarch-generic",
action="store_true",
dest="use_noarch_generic",
help="Mark packages that do not need compilation as `noarch: generic`",
)
cran.add_argument(
"--use-rtools-win",
action="store_true",
help="Use Rtools when building from source on Windows",
)
cran.add_argument(
"--recursive",
action="store_true",
help="Create recipes for dependencies if they do not already exist.",
)
cran.add_argument(
"--no-recursive",
action="store_false",
dest="recursive",
help="Don't create recipes for dependencies if they do not already exist.",
)
cran.add_argument(
"--no-archive",
action="store_false",
dest="archive",
help="Don't include an Archive download url.",
)
cran.add_argument(
"--allow-archived",
action="store_true",
dest="allow_archived",
help="If the package has been archived, download the latest version.",
)
cran.add_argument(
"--version-compare",
action="store_true",
help="""Compare the package version of the recipe with the one available
on CRAN. Exits 1 if a newer version is available and 0 otherwise.""",
)
cran.add_argument(
"--update-policy",
action="store",
choices=(
"error",
"skip-up-to-date",
"skip-existing",
"overwrite",
"merge-keep-build-num",
"merge-incr-build-num",
),
default="error",
help="""Dictates what to do when existing packages are encountered in the
output directory (set by --output-dir). In the present implementation, the
merge options avoid overwriting bld.bat and build.sh and only manage copying
across patches, and the `build/{number,script_env}` fields. When the version
changes, both merge options reset `build/number` to 0. When the version does
not change they either keep the old `build/number` or else increase it by one.""",
)
cran.add_argument(
"-m",
"--variant-config-files",
default=context.conda_build.get("skeleton_config_yaml", None),
help="""Variant config file to add. These yaml files can contain
keys such as `cran_mirror`. Only one can be provided here.""",
)
cran.add_argument(
"--add-cross-r-base",
action="store_true",
default=False,
help="""Add cross-r-base to build requirements for cross compiling""",
)
cran.add_argument(
"--no-comments",
action="store_true",
default=False,
help="""Do not include instructional comments in recipe files""",
)
def dict_from_cran_lines(lines):
d = {}
for line in lines:
if not line:
continue
try:
if ": " in line:
(k, v) = line.split(": ", 1)
else:
# Sometimes fields are included but left blank, e.g.:
# - Enhances in data.tree
# - Suggests in corpcor
(k, v) = line.split(":", 1)
except ValueError:
sys.exit("Error: Could not parse metadata (%s)" % line)
d[k] = v
# if k not in CRAN_KEYS:
# print("Warning: Unknown key %s" % k)
d["orig_lines"] = lines
return d
def remove_package_line_continuations(chunk):
"""
>>> chunk = [
'Package: A3',
'Version: 0.9.2',
'Depends: R (>= 2.15.0), xtable, pbapply',
'Suggests: randomForest, e1071',
'Imports: MASS, R.methodsS3 (>= 1.5.2), R.oo (>= 1.15.8), R.utils (>=',
' 1.27.1), matrixStats (>= 0.8.12), R.filesets (>= 2.3.0), ',
' sampleSelection, scatterplot3d, strucchange, systemfit',
'License: GPL (>= 2)',
'NeedsCompilation: no']
>>> remove_package_line_continuations(chunk)
['Package: A3',
'Version: 0.9.2',
'Depends: R (>= 2.15.0), xtable, pbapply',
'Suggests: randomForest, e1071',
'Imports: MASS, R.methodsS3 (>= 1.5.2), R.oo (>= 1.15.8), R.utils (>= 1.27.1), matrixStats (>= 0.8.12), R.filesets (>= 2.3.0), sampleSelection, scatterplot3d, strucchange, systemfit, rgl,'
'License: GPL (>= 2)',
'NeedsCompilation: no']
""" # NOQA
continuation = (" ", "\t")
continued_ix = None
continued_line = None
had_continuation = False
accumulating_continuations = False
chunk.append("")
for i, line in enumerate(chunk):
if line.startswith(continuation):
line = " " + line.lstrip()
if accumulating_continuations:
assert had_continuation
continued_line += line
chunk[i] = None
else:
accumulating_continuations = True
continued_ix = i - 1
continued_line = chunk[continued_ix] + line
had_continuation = True
chunk[i] = None
else:
if accumulating_continuations:
assert had_continuation
chunk[continued_ix] = continued_line
accumulating_continuations = False
continued_line = None
continued_ix = None
if had_continuation:
# Remove the None(s).
chunk = [c for c in chunk if c]
chunk.append("")
return chunk
def yaml_quote_string(string):
"""
Quote a string for use in YAML.
We can't just use yaml.dump because it adds ellipses to the end of the
string, and it in general doesn't handle being placed inside an existing
document very well.
Note that this function is NOT general.
"""
return (
yaml.dump(string, indent=True, Dumper=SafeDumper)
.replace("\n...\n", "")
.replace("\n", "\n ")
.rstrip("\n ")
)
# Due to how we render the metadata there can be significant areas of repeated newlines.
# This collapses them and also strips any trailing spaces.
def clear_whitespace(string):
lines = []
last_line = ""
for line in string.splitlines():
line = line.rstrip()
if not (line == "" and last_line == ""):
lines.append(line)
last_line = line
return "\n".join(lines)
def read_description_contents(fp):
bytes = fp.read()
text = bytes.decode("utf-8", errors="replace")
text = clear_whitespace(text)
lines = remove_package_line_continuations(text.splitlines())
return dict_from_cran_lines(lines)
def get_archive_metadata(path, verbose=True):
if verbose:
print("Reading package metadata from %s" % path)
if basename(path) == "DESCRIPTION":
with open(path, "rb") as fp:
return read_description_contents(fp)
elif tarfile.is_tarfile(path):
with tarfile.open(path, "r") as tf:
for member in tf:
if re.match(r"^[^/]+/DESCRIPTION$", member.name):
fp = tf.extractfile(member)
return read_description_contents(fp)
elif path.endswith(".zip"):
with zipfile.ZipFile(path, "r") as zf:
for member in zf.infolist():
if re.match(r"^[^/]+/DESCRIPTION$", member.filename):
fp = zf.open(member, "r")
return read_description_contents(fp)
else:
sys.exit("Cannot extract a DESCRIPTION from file %s" % path)
sys.exit("%s does not seem to be a CRAN package (no DESCRIPTION) file" % path)
def get_latest_git_tag(config):
# SO says to use taggerdate instead of committerdate, but that is invalid for lightweight tags.
p = subprocess.Popen(
[
"git",
"for-each-ref",
"refs/tags",
"--sort=-committerdate",
"--format=%(refname:short)",
"--count=1",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=config.work_dir,
)
stdout, stderr = p.communicate()
stdout = stdout.decode("utf-8")
stderr = stderr.decode("utf-8")
if stderr or p.returncode:
sys.exit("Error: git tag failed (%s)" % stderr)
tags = stdout.strip().splitlines()
if not tags:
sys.exit("Error: no tags found")
print("Using tag %s" % tags[-1])
return tags[-1]
def _ssl_no_verify():
"""Gets whether the SSL_NO_VERIFY environment variable is set to 1 or True.
This provides a workaround for users in some corporate environments where
MITM style proxies make it difficult to fetch data over HTTPS.
"""
return environ.get("SSL_NO_VERIFY", "").strip().lower() in ("1", "true")
def get_session(output_dir, verbose=True):
session = requests.Session()
session.verify = _ssl_no_verify()
try:
import cachecontrol
import cachecontrol.caches
except ImportError:
if verbose:
print(
"Tip: install CacheControl and lockfile (conda packages) to cache the "
"CRAN metadata"
)
else:
session = cachecontrol.CacheControl(
session, cache=cachecontrol.caches.FileCache(join(output_dir, ".web_cache"))
)
return session
def get_cran_archive_versions(cran_url, session, package, verbose=True):
if verbose:
print(f"Fetching archived versions for package {package} from {cran_url}")
r = session.get(cran_url + "/src/contrib/Archive/" + package + "/")
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
print("No archive directory for package %s" % package)
return []
raise
versions = []
for p, dt in re.findall(
r'<td><a href="([^"]+)">\1</a></td>\s*<td[^>]*>([^<]*)</td>', r.text
):
if p.endswith(".tar.gz") and "_" in p:
name, version = p.rsplit(".", 2)[0].split("_", 1)
versions.append((dt.strip(), version))
return [v for dt, v in sorted(versions, reverse=True)]
def get_cran_index(cran_url, session, verbose=True):
if verbose:
print("Fetching main index from %s" % cran_url)
r = session.get(cran_url + "/src/contrib/")
r.raise_for_status()
records = {}
for p in re.findall(r'<td><a href="([^"]+)">\1</a></td>', r.text):
if p.endswith(".tar.gz") and "_" in p:
name, version = p.rsplit(".", 2)[0].split("_", 1)
records[name.lower()] = (name, version)
r = session.get(cran_url + "/src/contrib/Archive/")
r.raise_for_status()
for p in re.findall(r'<td><a href="([^"]+)/">\1/</a></td>', r.text):
if re.match(r"^[A-Za-z]", p):
records.setdefault(p.lower(), (p, None))
return records
def make_array(m, key, allow_empty=False):
result = []
try:
old_vals = m.get_value(key, [])
except:
old_vals = []
if old_vals or allow_empty:
result.append(key.split("/")[-1] + ":")
for old_val in old_vals:
result.append(f"{INDENT}{old_val}")
return result
def existing_recipe_dir(output_dir, output_suffix, package, version):
result = None
if version:
package = package + "-" + version.replace("-", "_")
if exists(join(output_dir, package)):
result = normpath(join(output_dir, package))
elif exists(join(output_dir, package + output_suffix)):
result = normpath(join(output_dir, package + output_suffix))
elif exists(join(output_dir, "r-" + package + output_suffix)):
result = normpath(join(output_dir, "r-" + package + output_suffix))
return result
def strip_end(string, end):
if string.endswith(end):
return string[: -len(end)]
return string
def package_to_inputs_dict(
output_dir, output_suffix, git_tag, package: str, version=None
):
"""
Converts `package` (*) into a tuple of:
pkg_name (without leading 'r-')
location (in a subdir of output_dir - may not exist - or at GitHub)
old_git_rev (from existing metadata, so corresponds to the *old* version)
metadata or None (if a recipe does *not* already exist)
(*) `package` could be:
1. A package name beginning (or not) with 'r-'
2. A GitHub URL
3. A file:// URL to a tarball
4. A relative path to a recipe from output_dir
5. An absolute path to a recipe (fatal unless in the output_dir hierarchy)
6. Any of the above ending (or not) in sep or '/'
So this function cleans all that up:
Some packages may be from GitHub but we'd like the user not to have to worry
about that on the command-line (for pre-existing recipes). Also, we may want
to get version information from them (or existing metadata to merge) so lets
load *all* existing recipes (later we will add or replace this metadata with
any that we create).
"""
if isfile(package):
return None
print("Parsing input package %s:" % package)
package = strip_end(package, "/")
package = strip_end(package, sep)
if "github.com" in package:
package = strip_end(package, ".git")
pkg_name = basename(package).lower()
pkg_name = strip_end(pkg_name, "-feedstock")
if output_suffix:
pkg_name = strip_end(pkg_name, output_suffix)
if pkg_name.startswith("r-"):
pkg_name = pkg_name[2:]
if package.startswith("file://"):
location = package.replace("file://", "")
pkg_filename = basename(location)
pkg_name = re.match(r"(.*)_(.*)", pkg_filename).group(1).lower()
existing_location = existing_recipe_dir(
output_dir, output_suffix, "r-" + pkg_name, version
)
elif isabs(package):
commp = commonprefix((package, output_dir))
if commp != output_dir:
raise RuntimeError(
f"package {package} specified with abs path outside of output-dir {output_dir}"
)
location = package
existing_location = existing_recipe_dir(
output_dir, output_suffix, "r-" + pkg_name, version
)
elif "github.com" in package:
location = package
existing_location = existing_recipe_dir(
output_dir, output_suffix, "r-" + pkg_name, version
)
else:
location = existing_location = existing_recipe_dir(
output_dir, output_suffix, package, version
)
m: MetaData | None
if existing_location:
try:
m = MetaData(existing_location)
except:
# Happens when the folder exists but contains no recipe.
m = None
else:
m = None
# It can still be the case that a package without 'github.com' in the location does really
# come from there, for that we need to inspect the existing metadata's source/git_url.
old_git_rev = git_tag
if location and m and "github.com" not in location:
git_url = m.get_value("source/git_url", "")
if "github.com" in git_url:
location = git_url
old_git_rev = m.get_value("source/git_rev", None)
vstr = "-" + version.replace("-", "_") if version else ""
new_location = join(output_dir, "r-" + pkg_name + vstr + output_suffix)
print(f".. name: {pkg_name} location: {location} new_location: {new_location}")
return {
"pkg-name": pkg_name,
"location": location,
"old-git-rev": old_git_rev,
"old-metadata": m,
"new-location": new_location,
"version": version,
}
def get_available_binaries(cran_url, details):
url = cran_url + "/" + details["dir"]
response = requests.get(url)
response.raise_for_status()
ext = details["ext"]
for filename in re.findall(r'<a href="([^"]*)">\1</a>', response.text):
if filename.endswith(ext):
pkg, _, ver = filename.rpartition("_")
ver, _, _ = ver.rpartition(ext)
details["binaries"].setdefault(pkg, []).append((ver, url + filename))
def remove_comments(template):
re_comment = re.compile(r"^\s*#\s")
lines = template.split("\n")
lines_no_comments = [line for line in lines if not re_comment.match(line)]
return "\n".join(lines_no_comments)
def skeletonize(
in_packages: list[str],
output_dir: str = ".",
output_suffix: str = "",
add_maintainer: str | None = None,
version: str | None = None,
git_tag: str | None = None,
cran_url: str | None = None,
recursive: bool = False,
archive: bool = True,
version_compare: bool = False,
update_policy: Literal[
"error",
"skip-up-to-date",
"skip-existing",
"overwrite",
"merge-keep-build-num",
"merge-incr-build-num",
]
| None = None,
r_interp: str = "r-base",
use_binaries_ver: str | None = None,
use_noarch_generic: bool = False,
use_when_no_binary: Literal["error", "src", "old", "old-src"] = "src",
use_rtools_win: bool = False,
config: Config | None = None,
variant_config_files: list[str] | None = None,
allow_archived: bool = False,
add_cross_r_base: bool = False,
no_comments: bool = False,
) -> None:
if (
use_when_no_binary != "error"
and use_when_no_binary != "src"
and use_when_no_binary != "old"
and use_when_no_binary != "old-src"
):
print(f"ERROR: --use_when_no_binary={use_when_no_binary} not yet implemented")
sys.exit(1)
m: MetaData
output_dir = realpath(output_dir)
config = get_or_merge_config(config, variant_config_files=variant_config_files)
if allow_archived and not archive:
print("ERROR: --no-archive and --allow-archived conflict")
sys.exit(1)
if not cran_url:
with TemporaryDirectory() as t:
_variant = get_package_variants(t, config)[0]
cran_url = ensure_list(
_variant.get("cran_mirror", DEFAULT_VARIANTS["cran_mirror"])
)[0]
if len(in_packages) > 1 and version_compare:
raise ValueError("--version-compare only works with one package at a time")
if update_policy == "error" and not in_packages:
raise ValueError("At least one package must be supplied")
package_dicts = {}
package_list = []
cran_url = cran_url.rstrip("/")
# Get cran index lazily so we don't have to go to CRAN
# for a github repo or a local tarball
cran_index = None
cran_layout_template = {
"source": {
"selector": "{others}",
"dir": "src/contrib/",
"ext": ".tar.gz",
# If we had platform filters we would change this to:
# build_for_linux or is_github_url or is_tarfile
"use_this": True,
},
"win-64": {
"selector": "win64",
"dir": f"bin/windows/contrib/{use_binaries_ver}/",
"ext": ".zip",
"use_this": True if use_binaries_ver else False,
},
"osx-64": {
"selector": "osx",
"dir": f"bin/macosx/el-capitan/contrib/{use_binaries_ver}/",
"ext": ".tgz",
"use_this": True if use_binaries_ver else False,
},
}
# Figure out what binaries are available once:
for archive_type, archive_details in cran_layout_template.items():
archive_details["binaries"] = dict()
if archive_type != "source" and archive_details["use_this"]:
get_available_binaries(cran_url, archive_details)
for package in in_packages:
inputs_dict = package_to_inputs_dict(
output_dir, output_suffix, git_tag, package, version
)
if inputs_dict:
package_dicts.update({inputs_dict["pkg-name"]: {"inputs": inputs_dict}})
for package_name, package_dict in package_dicts.items():
package_list.append(package_name)
while package_list:
inputs = package_dicts[package_list.pop()]["inputs"]
location = inputs["location"]
pkg_name = inputs["pkg-name"]
version = inputs["version"]
is_github_url = location and "github.com" in location
is_tarfile = location and isfile(location) and tarfile.is_tarfile(location)
is_archive = False
url = inputs["location"]
dir_path = inputs["new-location"]
print(f"Making/refreshing recipe for {pkg_name}")
# Bodges GitHub packages into cran_metadata
if is_tarfile:
cran_package = get_archive_metadata(location)
elif is_github_url or is_tarfile:
rm_rf(config.work_dir)
m = MetaData.fromdict({"source": {"git_url": location}}, config=config)
source.git_source(
m.get_section("source"), m.config.git_cache, m.config.work_dir
)
new_git_tag = git_tag if git_tag else get_latest_git_tag(config)
p = subprocess.Popen(