forked from readthedocs/readthedocs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
1450 lines (1233 loc) · 48.1 KB
/
config.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
# pylint: disable=too-many-lines
"""Build configuration for rtd."""
import copy
import os
import re
from contextlib import contextmanager
from functools import lru_cache
from django.conf import settings
from readthedocs.config.utils import list_to_dict, to_dict
from readthedocs.core.utils.filesystem import safe_open
from readthedocs.projects.constants import GENERIC
from .find import find_one
from .models import (
Build,
BuildJobs,
BuildTool,
BuildWithTools,
Conda,
Mkdocs,
Python,
PythonInstall,
PythonInstallRequirements,
Search,
Sphinx,
Submodules,
)
from .parser import ParseError, parse
from .validation import (
VALUE_NOT_FOUND,
ValidationError,
validate_bool,
validate_choice,
validate_dict,
validate_list,
validate_path,
validate_path_pattern,
validate_string,
)
__all__ = (
"ALL",
"load",
"BuildConfigV1",
"BuildConfigV2",
"ConfigError",
"ConfigOptionNotSupportedError",
"ConfigFileNotFound",
"DefaultConfigFileNotFound",
"InvalidConfig",
"PIP",
"SETUPTOOLS",
"LATEST_CONFIGURATION_VERSION",
)
ALL = 'all'
PIP = 'pip'
SETUPTOOLS = 'setuptools'
CONFIG_FILENAME_REGEX = r'^\.?readthedocs.ya?ml$'
CONFIG_NOT_SUPPORTED = 'config-not-supported'
VERSION_INVALID = 'version-invalid'
CONFIG_SYNTAX_INVALID = 'config-syntax-invalid'
CONFIG_REQUIRED = 'config-required'
CONFIG_FILE_REQUIRED = 'config-file-required'
PYTHON_INVALID = 'python-invalid'
SUBMODULES_INVALID = 'submodules-invalid'
INVALID_KEYS_COMBINATION = 'invalid-keys-combination'
INVALID_KEY = 'invalid-key'
INVALID_NAME = 'invalid-name'
LATEST_CONFIGURATION_VERSION = 2
# TODO: make these exception to inherit from `BuildUserError`
class ConfigError(Exception):
"""Base error for the rtd configuration file."""
def __init__(self, message, code):
self.code = code
super().__init__(message)
class ConfigFileNotFound(ConfigError):
"""Error when we can't find a configuration file."""
def __init__(self, directory):
super().__init__(
f'Configuration file not found in: {directory}',
CONFIG_FILE_REQUIRED,
)
class DefaultConfigFileNotFound(ConfigError):
"""Error when we can't find a configuration file."""
def __init__(self, directory):
super().__init__(
f"No default configuration file in: {directory}",
CONFIG_FILE_REQUIRED,
)
class ConfigOptionNotSupportedError(ConfigError):
"""Error for unsupported configuration options in a version."""
def __init__(self, configuration):
self.configuration = configuration
template = (
'The "{}" configuration option is not supported in this version'
)
super().__init__(
template.format(self.configuration),
CONFIG_NOT_SUPPORTED,
)
class InvalidConfig(ConfigError):
"""Error for a specific key validation."""
message_template = 'Invalid "{key}": {error}'
def __init__(self, key, code, error_message, source_file=None):
self.key = key
self.code = code
self.source_file = source_file
message = self.message_template.format(
key=self._get_display_key(),
code=code,
error=error_message,
)
super().__init__(message, code=code)
def _get_display_key(self):
"""
Display keys in a more friendly format.
Indexes are displayed like ``n``,
but users may be more familiar with the ``[n]`` syntax.
For example ``python.install.0.requirements``
is changed to `python.install[0].requirements`.
"""
return re.sub(
r'^([a-zA-Z_.-]+)\.(\d+)([a-zA-Z_.-]*)$',
r'\1[\2]\3',
self.key
)
class BuildConfigBase:
"""
Config that handles the build of one particular documentation.
.. note::
You need to call ``validate`` before the config is ready to use.
:param env_config: A dict that contains additional information
about the environment.
:param raw_config: A dict with all configuration without validation.
:param source_file: The file that contains the configuration.
All paths are relative to this file.
If a dir is given, the configuration was loaded
from another source (like the web admin).
"""
PUBLIC_ATTRIBUTES = [
'version',
'formats',
'python',
'conda',
'build',
'doctype',
'sphinx',
'mkdocs',
'submodules',
'search',
]
default_build_image = settings.DOCKER_DEFAULT_VERSION
version = None
def __init__(self, env_config, raw_config, source_file):
self.env_config = env_config
self._raw_config = copy.deepcopy(raw_config)
self.source_config = copy.deepcopy(raw_config)
self.source_file = source_file
if os.path.isdir(self.source_file):
self.base_path = self.source_file
else:
self.base_path = os.path.dirname(self.source_file)
self.defaults = self.env_config.get('defaults', {})
self._config = {}
def error(self, key, message, code):
"""Raise an error related to ``key``."""
if not os.path.isdir(self.source_file):
source = os.path.relpath(self.source_file, self.base_path)
error_message = '{source}: {message}'.format(
source=source,
message=message,
)
else:
error_message = message
raise InvalidConfig(
key=key,
code=code,
error_message=error_message,
source_file=self.source_file,
)
@contextmanager
def catch_validation_error(self, key):
"""Catch a ``ValidationError`` and raises an ``InvalidConfig`` error."""
try:
yield
except ValidationError as error:
raise InvalidConfig(
key=key,
code=error.code,
error_message=str(error),
source_file=self.source_file,
)
def pop(self, name, container, default, raise_ex):
"""
Search and pop a key inside a dict.
This will pop the keys recursively if the container is empty.
:param name: the key name in a list form (``['key', 'inner']``)
:param container: a dictionary that contains the key
:param default: default value to return if the key doesn't exists
:param raise_ex: if True, raises an exception when a key is not found
"""
key = name[0]
validate_dict(container)
if key in container:
if len(name) > 1:
value = self.pop(name[1:], container[key], default, raise_ex)
if not container[key]:
container.pop(key)
else:
value = container.pop(key)
return value
if raise_ex:
raise ValidationError(key, VALUE_NOT_FOUND)
return default
def pop_config(self, key, default=None, raise_ex=False):
"""
Search and pop a key (recursively) from `self._raw_config`.
:param key: the key name in a dotted form (``key.innerkey``)
:param default: Optionally, it can receive a default value
:param raise_ex: If True, raises an exception when the key is not found
"""
return self.pop(key.split('.'), self._raw_config, default, raise_ex)
def validate(self):
raise NotImplementedError()
@property
def using_build_tools(self):
return isinstance(self.build, BuildWithTools)
@property
def is_using_conda(self):
if self.using_build_tools:
return self.python_interpreter in ("conda", "mamba")
return self.conda is not None
@property
def python_interpreter(self):
if self.using_build_tools:
tool = self.build.tools.get('python')
if tool and tool.version.startswith('mamba'):
return 'mamba'
if tool and tool.version.startswith('miniconda'):
return 'conda'
if tool:
return 'python'
return None
version = self.python_full_version
if version.startswith('pypy'):
# Allow to specify ``pypy3.5`` as Python interpreter
return version
return f'python{version}'
@property
def docker_image(self):
if self.using_build_tools:
return self.settings['os'][self.build.os]
return self.build.image
@property
def python_full_version(self):
version = self.python.version
if version in ['2', '3']:
# use default Python version if user only set '2', or '3'
return self.get_default_python_version_for_image(
self.build.image,
version,
)
return version
@property
def valid_build_images(self):
"""
Return all the valid Docker image choices for ``build.image`` option.
The user can use any of this values in the YAML file. These values are
the keys of ``DOCKER_IMAGE_SETTINGS`` Django setting (without the
``readthedocs/build`` part) plus ``stable``, ``latest`` and ``testing``.
"""
images = {'stable', 'latest', 'testing'}
for k in settings.DOCKER_IMAGE_SETTINGS:
_, version = k.split(':')
if re.fullmatch(r'^[\d\.]+$', version):
images.add(version)
return images
def get_valid_python_versions_for_image(self, build_image):
"""
Return all the valid Python versions for a Docker image.
The Docker image (``build_image``) has to be its complete name, already
validated: ``readthedocs/build:4.0``, not just ``4.0``.
Returns supported versions for the ``DOCKER_DEFAULT_VERSION`` if not
``build_image`` found.
"""
if build_image not in settings.DOCKER_IMAGE_SETTINGS:
build_image = '{}:{}'.format(
settings.DOCKER_DEFAULT_IMAGE,
self.default_build_image,
)
return settings.DOCKER_IMAGE_SETTINGS[build_image]['python']['supported_versions']
def get_default_python_version_for_image(self, build_image, python_version):
"""
Return the default Python version for Docker image and Py2 or Py3.
:param build_image: the Docker image complete name, already validated
(``readthedocs/build:4.0``, not just ``4.0``)
:type build_image: str
:param python_version: major Python version (``2`` or ``3``) to get its
default full version
:type python_version: int
:returns: default version for the ``DOCKER_DEFAULT_VERSION`` if not
``build_image`` found.
"""
if build_image not in settings.DOCKER_IMAGE_SETTINGS:
build_image = '{}:{}'.format(
settings.DOCKER_DEFAULT_IMAGE,
self.default_build_image,
)
return (
# For linting
settings.DOCKER_IMAGE_SETTINGS[build_image]['python']
['default_version'][python_version]
)
def as_dict(self):
config = {}
for name in self.PUBLIC_ATTRIBUTES:
attr = getattr(self, name)
config[name] = to_dict(attr)
return config
def __getattr__(self, name):
"""Raise an error for unknown attributes."""
raise ConfigOptionNotSupportedError(name)
class BuildConfigV1(BuildConfigBase):
"""Version 1 of the configuration file."""
PYTHON_INVALID_MESSAGE = '"python" section must be a mapping.'
PYTHON_EXTRA_REQUIREMENTS_INVALID_MESSAGE = (
'"python.extra_requirements" section must be a list.'
)
version = '1'
def get_valid_python_versions(self):
"""
Return all valid Python versions.
.. note::
It does not take current build image used into account.
"""
try:
return self.env_config['python']['supported_versions']
except (KeyError, TypeError):
versions = set()
for _, options in settings.DOCKER_IMAGE_SETTINGS.items():
versions = versions.union(
options['python']['supported_versions']
)
return versions
def get_valid_formats(self): # noqa
"""Get all valid documentation formats."""
return (
'htmlzip',
'pdf',
'epub',
)
def validate(self):
"""
Validate and process ``raw_config`` and ``env_config`` attributes.
It makes sure that:
- ``base`` is a valid directory and defaults to the directory of the
``readthedocs.yml`` config file if not set
"""
# Validate env_config.
# Validate the build environment first
# Must happen before `validate_python`!
self._config['build'] = self.validate_build()
# Validate raw_config. Order matters.
self._config['python'] = self.validate_python()
self._config['formats'] = self.validate_formats()
self._config['conda'] = self.validate_conda()
self._config['requirements_file'] = self.validate_requirements_file()
def validate_build(self):
"""
Validate the build config settings.
This is a bit complex,
so here is the logic:
* We take the default image & version if it's specific in the environment
* Then update the _version_ from the users config
* Then append the default _image_, since users can't change this
* Then update the env_config with the settings for that specific image
- This is currently used for a build image -> python version mapping
This means we can use custom docker _images_,
but can't change the supported _versions_ that users have defined.
"""
# Defaults
if 'build' in self.env_config:
build = self.env_config['build'].copy()
else:
build = {'image': settings.DOCKER_IMAGE}
# User specified
if 'build' in self._raw_config:
_build = self._raw_config['build']
if 'image' in _build:
with self.catch_validation_error('build'):
build['image'] = validate_choice(
str(_build['image']),
self.valid_build_images,
)
if ':' not in build['image']:
# Prepend proper image name to user's image name
build['image'] = '{}:{}'.format(
settings.DOCKER_DEFAULT_IMAGE,
build['image'],
)
# Update docker default settings from image name
if build['image'] in settings.DOCKER_IMAGE_SETTINGS:
self.env_config.update(
settings.DOCKER_IMAGE_SETTINGS[build['image']]
)
# Allow to override specific project
config_image = self.defaults.get('build_image')
if config_image:
build['image'] = config_image
return build
def validate_python(self):
"""Validates the ``python`` key, set default values it's necessary."""
install_project = self.defaults.get('install_project', False)
use_system_packages = self.defaults.get('use_system_packages', False)
version = self.defaults.get('python_version', '2')
python = {
'use_system_site_packages': use_system_packages,
'install_with_pip': False,
'extra_requirements': [],
'install_with_setup': install_project,
'version': version,
}
if 'python' in self._raw_config:
raw_python = self._raw_config['python']
if not isinstance(raw_python, dict):
self.error(
'python',
self.PYTHON_INVALID_MESSAGE,
code=PYTHON_INVALID,
)
# Validate use_system_site_packages.
if 'use_system_site_packages' in raw_python:
with self.catch_validation_error('python.use_system_site_packages'):
python['use_system_site_packages'] = validate_bool(
raw_python['use_system_site_packages'],
)
# Validate pip_install.
if 'pip_install' in raw_python:
with self.catch_validation_error('python.pip_install'):
python['install_with_pip'] = validate_bool(
raw_python['pip_install'],
)
# Validate extra_requirements.
if 'extra_requirements' in raw_python:
raw_extra_requirements = raw_python['extra_requirements']
if not isinstance(raw_extra_requirements, list):
self.error(
'python.extra_requirements',
self.PYTHON_EXTRA_REQUIREMENTS_INVALID_MESSAGE,
code=PYTHON_INVALID,
)
if not python['install_with_pip']:
python['extra_requirements'] = []
else:
for extra_name in raw_extra_requirements:
with self.catch_validation_error('python.extra_requirements'):
python['extra_requirements'].append(
validate_string(extra_name),
)
# Validate setup_py_install.
if 'setup_py_install' in raw_python:
with self.catch_validation_error('python.setup_py_install'):
python['install_with_setup'] = validate_bool(
raw_python['setup_py_install'],
)
if 'version' in raw_python:
with self.catch_validation_error('python.version'):
version = str(raw_python['version'])
python['version'] = validate_choice(
version,
self.get_valid_python_versions(),
)
return python
def validate_conda(self):
"""Validates the ``conda`` key."""
conda = {}
if 'conda' in self._raw_config:
raw_conda = self._raw_config['conda']
with self.catch_validation_error('conda'):
validate_dict(raw_conda)
with self.catch_validation_error('conda.file'):
if 'file' not in raw_conda:
raise ValidationError('file', VALUE_NOT_FOUND)
conda_environment = validate_path(
raw_conda['file'],
self.base_path,
)
conda['environment'] = conda_environment
return conda
return None
def validate_requirements_file(self):
"""Validates that the requirements file exists."""
if 'requirements_file' not in self._raw_config:
requirements_file = self.defaults.get('requirements_file')
else:
requirements_file = self._raw_config['requirements_file']
if not requirements_file:
return None
with self.catch_validation_error('requirements_file'):
requirements_file = validate_path(
requirements_file,
self.base_path,
)
return requirements_file
def validate_formats(self):
"""Validates that formats contains only valid formats."""
formats = self._raw_config.get('formats')
if formats is None:
return self.defaults.get('formats', [])
if formats == ['none']:
return []
with self.catch_validation_error('format'):
validate_list(formats)
for format_ in formats:
validate_choice(format_, self.get_valid_formats())
return formats
@property
def formats(self):
"""The documentation formats to be built."""
return self._config['formats']
@property
def python(self):
"""Python related configuration."""
python = self._config['python']
requirements = self._config['requirements_file']
python_install = []
# Always append a `PythonInstallRequirements` option.
# If requirements is None, rtd will try to find a requirements file.
python_install.append(
PythonInstallRequirements(
requirements=requirements,
),
)
if python['install_with_pip']:
python_install.append(
PythonInstall(
path=self.base_path,
method=PIP,
extra_requirements=python['extra_requirements'],
),
)
elif python['install_with_setup']:
python_install.append(
PythonInstall(
path=self.base_path,
method=SETUPTOOLS,
extra_requirements=[],
),
)
return Python(
version=python['version'],
install=python_install,
use_system_site_packages=python['use_system_site_packages'],
)
@property
def conda(self):
if self._config['conda'] is not None:
return Conda(**self._config['conda'])
return None
@property
@lru_cache(maxsize=1)
def build(self):
"""The docker image used by the builders."""
return Build(**self._config['build'])
@property
def doctype(self):
return self.defaults['doctype']
@property
def sphinx(self):
config_file = self.defaults['sphinx_configuration']
if config_file is not None:
config_file = os.path.join(self.base_path, config_file)
return Sphinx(
builder=self.doctype,
configuration=config_file,
fail_on_warning=False,
)
@property
def mkdocs(self):
return Mkdocs(
configuration=None,
fail_on_warning=False,
)
@property
def submodules(self):
return Submodules(
include=ALL,
exclude=[],
recursive=True,
)
@property
def search(self):
return Search(ranking={}, ignore=[])
class BuildConfigV2(BuildConfigBase):
"""Version 2 of the configuration file."""
version = '2'
valid_formats = ['htmlzip', 'pdf', 'epub']
valid_install_method = [PIP, SETUPTOOLS]
valid_sphinx_builders = {
'html': 'sphinx',
'htmldir': 'sphinx_htmldir',
'dirhtml': 'sphinx_htmldir',
'singlehtml': 'sphinx_singlehtml',
}
@property
def settings(self):
return settings.RTD_DOCKER_BUILD_SETTINGS
def validate(self):
"""
Validates and process ``raw_config`` and ``env_config``.
Sphinx is the default doc type to be built. We don't merge some values
from the database (like formats or python.version) to allow us set
default values.
"""
self._config['formats'] = self.validate_formats()
self._config['conda'] = self.validate_conda()
# This should be called before validate_python
self._config['build'] = self.validate_build()
self._config['python'] = self.validate_python()
# Call this before validate sphinx and mkdocs
self.validate_doc_types()
self._config['mkdocs'] = self.validate_mkdocs()
self._config['sphinx'] = self.validate_sphinx()
self._config['submodules'] = self.validate_submodules()
self._config['search'] = self.validate_search()
self.validate_keys()
def validate_formats(self):
"""
Validates that formats contains only valid formats.
The ``ALL`` keyword can be used to indicate that all formats are used.
We ignore the default values here.
"""
formats = self.pop_config('formats', [])
if formats == ALL:
return self.valid_formats
with self.catch_validation_error('formats'):
validate_list(formats)
for format_ in formats:
validate_choice(format_, self.valid_formats)
return formats
def validate_conda(self):
"""Validates the conda key."""
raw_conda = self._raw_config.get('conda')
if raw_conda is None:
return None
with self.catch_validation_error('conda'):
validate_dict(raw_conda)
conda = {}
with self.catch_validation_error('conda.environment'):
environment = self.pop_config('conda.environment', raise_ex=True)
conda['environment'] = validate_path(environment, self.base_path)
return conda
# NOTE: I think we should rename `BuildWithTools` to `BuildWithOs` since
# `os` is the main and mandatory key that makes the diference
#
# NOTE: `build.jobs` can't be used without using `build.os`
def validate_build_config_with_tools(self):
"""
Validates the build object (new format).
At least one element must be provided in ``build.tools``.
"""
build = {}
with self.catch_validation_error('build.os'):
build_os = self.pop_config('build.os', raise_ex=True)
build['os'] = validate_choice(build_os, self.settings['os'].keys())
tools = {}
with self.catch_validation_error('build.tools'):
tools = self.pop_config('build.tools')
validate_dict(tools)
for tool in tools.keys():
validate_choice(tool, self.settings['tools'].keys())
jobs = {}
with self.catch_validation_error("build.jobs"):
# FIXME: should we use `default={}` or kept the `None` here and
# shortcircuit the rest of the logic?
jobs = self.pop_config("build.jobs", default={})
validate_dict(jobs)
# NOTE: besides validating that each key is one of the expected
# ones, we could validate the value of each of them is a list of
# commands. However, I don't think we should validate the "command"
# looks like a real command.
for job in jobs.keys():
validate_choice(
job,
BuildJobs.__slots__,
)
commands = []
with self.catch_validation_error("build.commands"):
commands = self.pop_config("build.commands", default=[])
validate_list(commands)
if not tools:
self.error(
key='build.tools',
message=(
'At least one tools of [{}] must be provided.'.format(
' ,'.join(self.settings['tools'].keys())
)
),
code=CONFIG_REQUIRED,
)
if commands and jobs:
self.error(
key="build.commands",
message="The keys build.jobs and build.commands can't be used together.",
code=INVALID_KEYS_COMBINATION,
)
build["jobs"] = {}
for job, job_commands in jobs.items():
with self.catch_validation_error(f"build.jobs.{job}"):
build["jobs"][job] = [
validate_string(job_command)
for job_command in validate_list(job_commands)
]
build["commands"] = []
for command in commands:
with self.catch_validation_error("build.commands"):
build["commands"].append(validate_string(command))
build['tools'] = {}
for tool, version in tools.items():
with self.catch_validation_error(f'build.tools.{tool}'):
build['tools'][tool] = validate_choice(
version,
self.settings['tools'][tool].keys(),
)
build['apt_packages'] = self.validate_apt_packages()
return build
def validate_old_build_config(self):
"""
Validates the build object (old format).
It prioritizes the value from the default image if exists.
"""
build = {}
with self.catch_validation_error('build.image'):
image = self.pop_config('build.image', self.default_build_image)
build['image'] = '{}:{}'.format(
settings.DOCKER_DEFAULT_IMAGE,
validate_choice(
image,
self.valid_build_images,
),
)
# Allow to override specific project
config_image = self.defaults.get('build_image')
if config_image:
build['image'] = config_image
build['apt_packages'] = self.validate_apt_packages()
return build
def validate_apt_packages(self):
apt_packages = []
with self.catch_validation_error('build.apt_packages'):
raw_packages = self._raw_config.get('build', {}).get('apt_packages', [])
validate_list(raw_packages)
# Transform to a dict, so is easy to validate individual entries.
self._raw_config.setdefault('build', {})['apt_packages'] = (
list_to_dict(raw_packages)
)
apt_packages = [
self.validate_apt_package(index)
for index in range(len(raw_packages))
]
if not raw_packages:
self.pop_config('build.apt_packages')
return apt_packages
def validate_build(self):
raw_build = self._raw_config.get('build', {})
with self.catch_validation_error('build'):
validate_dict(raw_build)
if 'os' in raw_build:
return self.validate_build_config_with_tools()
return self.validate_old_build_config()
def validate_apt_package(self, index):
"""
Validate the package name to avoid injections of extra options.
We validate that they aren't interpreted as an option or file.
See https://manpages.ubuntu.com/manpages/xenial/man8/apt-get.8.html
and https://www.debian.org/doc/manuals/debian-reference/ch02.en.html#_debian_package_file_names # noqa
for allowed chars in packages names.
"""
key = f'build.apt_packages.{index}'
package = self.pop_config(key)
with self.catch_validation_error(key):
validate_string(package)
package = package.strip()
invalid_starts = [
# Don't allow extra options.
'-',
# Don't allow to install from a path.
'/',
'.',
]
for start in invalid_starts:
if package.startswith(start):
self.error(
key=key,
message=(
'Invalid package name. '
f'Package can\'t start with {start}.',
),
code=INVALID_NAME,
)
# List of valid chars in packages names.
pattern = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9.+-]*$')
if not pattern.match(package):
self.error(
key=key,
message='Invalid package name.',
code=INVALID_NAME,
)
return package
def validate_python(self):
"""
Validates the python key.
validate_build should be called before this, since it initialize the
build.image attribute.
Fall back to the defaults of:
- ``requirements``
- ``install`` (only for setup.py method)
- ``system_packages``
.. note::
- ``version`` can be a string or number type.
- ``extra_requirements`` needs to be used with ``install: 'pip'``.
- If the new build config is used (``build.os``),
``python.version`` shouldn't exist.
"""
raw_python = self._raw_config.get('python', {})
with self.catch_validation_error('python'):
validate_dict(raw_python)
python = {}
if not self.using_build_tools:
with self.catch_validation_error('python.version'):
version = self.pop_config('python.version', '3')
if version == 3.1:
# Special case for ``python.version: 3.10``,
# yaml will transform this to the numeric value of `3.1`.
# Save some frustration to users.
version = '3.10'
version = str(version)
python['version'] = validate_choice(
version,
self.get_valid_python_versions(),
)
with self.catch_validation_error('python.install'):
raw_install = self._raw_config.get('python', {}).get('install', [])
validate_list(raw_install)
if raw_install:
# Transform to a dict, so it's easy to validate extra keys.
self._raw_config.setdefault('python', {})['install'] = (
list_to_dict(raw_install)
)
else:
self.pop_config('python.install')