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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
|
import argparse
import os
import random
from fnmatch import fnmatchcase
import sys
import re
import shlex
import string
import pkg_resources
import itertools
import pluggy
import tox.interpreters
from tox import hookspecs
import py
import tox
iswin32 = sys.platform == "win32"
default_factors = {'jython': 'jython', 'pypy': 'pypy', 'pypy3': 'pypy3',
'py': sys.executable}
for version in '26,27,32,33,34,35,36'.split(','):
default_factors['py' + version] = 'python%s.%s' % tuple(version)
hookimpl = pluggy.HookimplMarker("tox")
def get_plugin_manager():
# initialize plugin manager
pm = pluggy.PluginManager("tox")
pm.add_hookspecs(hookspecs)
pm.register(tox.config)
pm.register(tox.interpreters)
pm.load_setuptools_entrypoints("tox")
pm.check_pending()
return pm
class Parser:
""" command line and ini-parser control object. """
def __init__(self):
self.argparser = argparse.ArgumentParser(
description="tox options", add_help=False)
self._testenv_attr = []
def add_argument(self, *args, **kwargs):
""" add argument to command line parser. This takes the
same arguments that ``argparse.ArgumentParser.add_argument``.
"""
return self.argparser.add_argument(*args, **kwargs)
def add_testenv_attribute(self, name, type, help, default=None, postprocess=None):
""" add an ini-file variable for "testenv" section.
Types are specified as strings like "bool", "line-list", "string", "argv", "path",
"argvlist".
The ``postprocess`` function will be called for each testenv
like ``postprocess(testenv_config=testenv_config, value=value)``
where ``value`` is the value as read from the ini (or the default value)
and ``testenv_config`` is a :py:class:`tox.config.TestenvConfig` instance
which will receive all ini-variables as object attributes.
Any postprocess function must return a value which will then be set
as the final value in the testenv section.
"""
self._testenv_attr.append(VenvAttribute(name, type, default, help, postprocess))
def add_testenv_attribute_obj(self, obj):
""" add an ini-file variable as an object.
This works as the ``add_testenv_attribute`` function but expects
"name", "type", "help", and "postprocess" attributes on the object.
"""
assert hasattr(obj, "name")
assert hasattr(obj, "type")
assert hasattr(obj, "help")
assert hasattr(obj, "postprocess")
self._testenv_attr.append(obj)
def _parse_args(self, args):
return self.argparser.parse_args(args)
def _format_help(self):
return self.argparser.format_help()
class VenvAttribute:
def __init__(self, name, type, default, help, postprocess):
self.name = name
self.type = type
self.default = default
self.help = help
self.postprocess = postprocess
class DepOption:
name = "deps"
type = "line-list"
help = "each line specifies a dependency in pip/setuptools format."
default = ()
def postprocess(self, testenv_config, value):
deps = []
config = testenv_config.config
for depline in value:
m = re.match(r":(\w+):\s*(\S+)", depline)
if m:
iname, name = m.groups()
ixserver = config.indexserver[iname]
else:
name = depline.strip()
ixserver = None
name = self._replace_forced_dep(name, config)
deps.append(DepConfig(name, ixserver))
return deps
def _replace_forced_dep(self, name, config):
"""
Override the given dependency config name taking --force-dep-version
option into account.
:param name: dep config, for example ["pkg==1.0", "other==2.0"].
:param config: Config instance
:return: the new dependency that should be used for virtual environments
"""
if not config.option.force_dep:
return name
for forced_dep in config.option.force_dep:
if self._is_same_dep(forced_dep, name):
return forced_dep
return name
@classmethod
def _is_same_dep(cls, dep1, dep2):
"""
Returns True if both dependency definitions refer to the
same package, even if versions differ.
"""
dep1_name = pkg_resources.Requirement.parse(dep1).project_name
try:
dep2_name = pkg_resources.Requirement.parse(dep2).project_name
except pkg_resources.RequirementParseError:
# we couldn't parse a version, probably a URL
return False
return dep1_name == dep2_name
class PosargsOption:
name = "args_are_paths"
type = "bool"
default = True
help = "treat positional args in commands as paths"
def postprocess(self, testenv_config, value):
config = testenv_config.config
args = config.option.args
if args:
if value:
args = []
for arg in config.option.args:
if arg:
origpath = config.invocationcwd.join(arg, abs=True)
if origpath.check():
arg = testenv_config.changedir.bestrelpath(origpath)
args.append(arg)
testenv_config._reader.addsubstitutions(args)
return value
class InstallcmdOption:
name = "install_command"
type = "argv"
default = "pip install {opts} {packages}"
help = "install command for dependencies and package under test."
def postprocess(self, testenv_config, value):
if '{packages}' not in value:
raise tox.exception.ConfigError(
"'install_command' must contain '{packages}' substitution")
return value
def parseconfig(args=None):
"""
:param list[str] args: Optional list of arguments.
:type pkg: str
:rtype: :class:`Config`
:raise SystemExit: toxinit file is not found
"""
pm = get_plugin_manager()
if args is None:
args = sys.argv[1:]
# prepare command line options
parser = Parser()
pm.hook.tox_addoption(parser=parser)
# parse command line options
option = parser._parse_args(args)
interpreters = tox.interpreters.Interpreters(hook=pm.hook)
config = Config(pluginmanager=pm, option=option, interpreters=interpreters)
config._parser = parser
config._testenv_attr = parser._testenv_attr
# parse ini file
basename = config.option.configfile
if os.path.isabs(basename):
inipath = py.path.local(basename)
else:
for path in py.path.local().parts(reverse=True):
inipath = path.join(basename)
if inipath.check():
break
else:
feedback("toxini file %r not found" % (basename), sysexit=True)
try:
parseini(config, inipath)
except tox.exception.InterpreterNotFound:
exn = sys.exc_info()[1]
# Use stdout to match test expectations
py.builtin.print_("ERROR: " + str(exn))
# post process config object
pm.hook.tox_configure(config=config)
return config
def feedback(msg, sysexit=False):
py.builtin.print_("ERROR: " + msg, file=sys.stderr)
if sysexit:
raise SystemExit(1)
class VersionAction(argparse.Action):
def __call__(self, argparser, *args, **kwargs):
version = tox.__version__
py.builtin.print_("%s imported from %s" % (version, tox.__file__))
raise SystemExit(0)
class CountAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if hasattr(namespace, self.dest):
setattr(namespace, self.dest, int(getattr(namespace, self.dest)) + 1)
else:
setattr(namespace, self.dest, 0)
@hookimpl
def tox_addoption(parser):
# formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--version", nargs=0, action=VersionAction,
dest="version",
help="report version information to stdout.")
parser.add_argument("-h", "--help", action="store_true", dest="help",
help="show help about options")
parser.add_argument("--help-ini", "--hi", action="store_true", dest="helpini",
help="show help about ini-names")
parser.add_argument("-v", nargs=0, action=CountAction, default=0,
dest="verbosity",
help="increase verbosity of reporting output.")
parser.add_argument("--showconfig", action="store_true",
help="show configuration information for all environments. ")
parser.add_argument("-l", "--listenvs", action="store_true",
dest="listenvs", help="show list of test environments")
parser.add_argument("-c", action="store", default="tox.ini",
dest="configfile",
help="use the specified config file name.")
parser.add_argument("-e", action="append", dest="env",
metavar="envlist",
help="work against specified environments (ALL selects all).")
parser.add_argument("--notest", action="store_true", dest="notest",
help="skip invoking test commands.")
parser.add_argument("--sdistonly", action="store_true", dest="sdistonly",
help="only perform the sdist packaging activity.")
parser.add_argument("--installpkg", action="store", default=None,
metavar="PATH",
help="use specified package for installation into venv, instead of "
"creating an sdist.")
parser.add_argument("--develop", action="store_true", dest="develop",
help="install package in the venv using 'setup.py develop' via "
"'pip -e .'")
parser.add_argument('-i', action="append",
dest="indexurl", metavar="URL",
help="set indexserver url (if URL is of form name=url set the "
"url for the 'name' indexserver, specifically)")
parser.add_argument("--pre", action="store_true", dest="pre",
help="install pre-releases and development versions of dependencies. "
"This will pass the --pre option to install_command "
"(pip by default).")
parser.add_argument("-r", "--recreate", action="store_true",
dest="recreate",
help="force recreation of virtual environments")
parser.add_argument("--result-json", action="store",
dest="resultjson", metavar="PATH",
help="write a json file with detailed information "
"about all commands and results involved.")
# We choose 1 to 4294967295 because it is the range of PYTHONHASHSEED.
parser.add_argument("--hashseed", action="store",
metavar="SEED", default=None,
help="set PYTHONHASHSEED to SEED before running commands. "
"Defaults to a random integer in the range [1, 4294967295] "
"([1, 1024] on Windows). "
"Passing 'noset' suppresses this behavior.")
parser.add_argument("--force-dep", action="append",
metavar="REQ", default=None,
help="Forces a certain version of one of the dependencies "
"when configuring the virtual environment. REQ Examples "
"'pytest<2.7' or 'django>=1.6'.")
parser.add_argument("--sitepackages", action="store_true",
help="override sitepackages setting to True in all envs")
parser.add_argument("--skip-missing-interpreters", action="store_true",
help="don't fail tests for missing interpreters")
parser.add_argument("args", nargs="*",
help="additional arguments available to command positional substitution")
# add various core venv interpreter attributes
def basepython_default(testenv_config, value):
if value is None:
for f in testenv_config.factors:
if f in default_factors:
return default_factors[f]
return sys.executable
return str(value)
parser.add_testenv_attribute(
name="basepython", type="string", default=None, postprocess=basepython_default,
help="executable name or path of interpreter used to create a "
"virtual test environment.")
parser.add_testenv_attribute(
name="envdir", type="path", default="{toxworkdir}/{envname}",
help="venv directory")
parser.add_testenv_attribute(
name="envtmpdir", type="path", default="{envdir}/tmp",
help="venv temporary directory")
parser.add_testenv_attribute(
name="envlogdir", type="path", default="{envdir}/log",
help="venv log directory")
def downloadcache(testenv_config, value):
if value:
# env var, if present, takes precedence
downloadcache = os.environ.get("PIP_DOWNLOAD_CACHE", value)
return py.path.local(downloadcache)
parser.add_testenv_attribute(
name="downloadcache", type="string", default=None, postprocess=downloadcache,
help="(deprecated) set PIP_DOWNLOAD_CACHE.")
parser.add_testenv_attribute(
name="changedir", type="path", default="{toxinidir}",
help="directory to change to when running commands")
parser.add_testenv_attribute_obj(PosargsOption())
parser.add_testenv_attribute(
name="skip_install", type="bool", default=False,
help="Do not install the current package. This can be used when "
"you need the virtualenv management but do not want to install "
"the current package")
parser.add_testenv_attribute(
name="ignore_errors", type="bool", default=False,
help="if set to True all commands will be executed irrespective of their "
"result error status.")
def recreate(testenv_config, value):
if testenv_config.config.option.recreate:
return True
return value
parser.add_testenv_attribute(
name="recreate", type="bool", default=False, postprocess=recreate,
help="always recreate this test environment.")
def setenv(testenv_config, value):
setenv = value
config = testenv_config.config
if "PYTHONHASHSEED" not in setenv and config.hashseed is not None:
setenv['PYTHONHASHSEED'] = config.hashseed
return setenv
parser.add_testenv_attribute(
name="setenv", type="dict", postprocess=setenv,
help="list of X=Y lines with environment variable settings")
def passenv(testenv_config, value):
# Flatten the list to deal with space-separated values.
value = list(
itertools.chain.from_iterable(
[x.split(' ') for x in value]))
passenv = set(["PATH", "PIP_INDEX_URL", "LANG", "LD_LIBRARY_PATH"])
# read in global passenv settings
p = os.environ.get("TOX_TESTENV_PASSENV", None)
if p is not None:
passenv.update(x for x in p.split() if x)
# we ensure that tmp directory settings are passed on
# we could also set it to the per-venv "envtmpdir"
# but this leads to very long paths when run with jenkins
# so we just pass it on by default for now.
if sys.platform == "win32":
passenv.add("SYSTEMDRIVE") # needed for pip6
passenv.add("SYSTEMROOT") # needed for python's crypto module
passenv.add("PATHEXT") # needed for discovering executables
passenv.add("TEMP")
passenv.add("TMP")
else:
passenv.add("TMPDIR")
for spec in value:
for name in os.environ:
if fnmatchcase(name.upper(), spec.upper()):
passenv.add(name)
return passenv
parser.add_testenv_attribute(
name="passenv", type="line-list", postprocess=passenv,
help="environment variables needed during executing test commands "
"(taken from invocation environment). Note that tox always "
"passes through some basic environment variables which are "
"needed for basic functioning of the Python system. "
"See --showconfig for the eventual passenv setting.")
parser.add_testenv_attribute(
name="whitelist_externals", type="line-list",
help="each lines specifies a path or basename for which tox will not warn "
"about it coming from outside the test environment.")
parser.add_testenv_attribute(
name="platform", type="string", default=".*",
help="regular expression which must match against ``sys.platform``. "
"otherwise testenv will be skipped.")
def sitepackages(testenv_config, value):
return testenv_config.config.option.sitepackages or value
parser.add_testenv_attribute(
name="sitepackages", type="bool", default=False, postprocess=sitepackages,
help="Set to ``True`` if you want to create virtual environments that also "
"have access to globally installed packages.")
def pip_pre(testenv_config, value):
return testenv_config.config.option.pre or value
parser.add_testenv_attribute(
name="pip_pre", type="bool", default=False, postprocess=pip_pre,
help="If ``True``, adds ``--pre`` to the ``opts`` passed to "
"the install command. ")
def develop(testenv_config, value):
option = testenv_config.config.option
return not option.installpkg and (value or option.develop)
parser.add_testenv_attribute(
name="usedevelop", type="bool", postprocess=develop, default=False,
help="install package in develop/editable mode")
parser.add_testenv_attribute_obj(InstallcmdOption())
parser.add_testenv_attribute_obj(DepOption())
parser.add_testenv_attribute(
name="commands", type="argvlist", default="",
help="each line specifies a test command and can use substitution.")
class Config(object):
""" Global Tox config object. """
def __init__(self, pluginmanager, option, interpreters):
#: dictionary containing envname to envconfig mappings
self.envconfigs = {}
self.invocationcwd = py.path.local()
self.interpreters = interpreters
self.pluginmanager = pluginmanager
#: option namespace containing all parsed command line options
self.option = option
@property
def homedir(self):
homedir = get_homedir()
if homedir is None:
homedir = self.toxinidir # XXX good idea?
return homedir
class TestenvConfig:
""" Testenv Configuration object.
In addition to some core attributes/properties this config object holds all
per-testenv ini attributes as attributes, see "tox --help-ini" for an overview.
"""
def __init__(self, envname, config, factors, reader):
#: test environment name
self.envname = envname
#: global tox config object
self.config = config
#: set of factors
self.factors = factors
self._reader = reader
@property
def envbindir(self):
""" path to directory where scripts/binaries reside. """
if (sys.platform == "win32"
and "jython" not in self.basepython
and "pypy" not in self.basepython):
return self.envdir.join("Scripts")
else:
return self.envdir.join("bin")
@property
def envpython(self):
""" path to python/jython executable. """
if "jython" in str(self.basepython):
name = "jython"
else:
name = "python"
return self.envbindir.join(name)
# no @property to avoid early calling (see callable(subst[key]) checks)
def envsitepackagesdir(self):
""" return sitepackagesdir of the virtualenv environment.
(only available during execution, not parsing)
"""
self.getsupportedinterpreter() # for throwing exceptions
x = self.config.interpreters.get_sitepackagesdir(
info=self.python_info,
envdir=self.envdir)
return x
@property
def python_info(self):
""" return sitepackagesdir of the virtualenv environment. """
return self.config.interpreters.get_info(envconfig=self)
def getsupportedinterpreter(self):
if sys.platform == "win32" and self.basepython and \
"jython" in self.basepython:
raise tox.exception.UnsupportedInterpreter(
"Jython/Windows does not support installing scripts")
info = self.config.interpreters.get_info(envconfig=self)
if not info.executable:
raise tox.exception.InterpreterNotFound(self.basepython)
if not info.version_info:
raise tox.exception.InvocationError(
'Failed to get version_info for %s: %s' % (info.name, info.err))
if info.version_info < (2, 6):
raise tox.exception.UnsupportedInterpreter(
"python2.5 is not supported anymore, sorry")
return info.executable
testenvprefix = "testenv:"
def get_homedir():
try:
return py.path.local._gethomedir()
except Exception:
return None
def make_hashseed():
max_seed = 4294967295
if sys.platform == 'win32':
max_seed = 1024
return str(random.randint(1, max_seed))
class parseini:
def __init__(self, config, inipath):
config.toxinipath = inipath
config.toxinidir = config.toxinipath.dirpath()
self._cfg = py.iniconfig.IniConfig(config.toxinipath)
config._cfg = self._cfg
self.config = config
ctxname = getcontextname()
if ctxname == "jenkins":
reader = SectionReader("tox:jenkins", self._cfg, fallbacksections=['tox'])
distshare_default = "{toxworkdir}/distshare"
elif not ctxname:
reader = SectionReader("tox", self._cfg)
distshare_default = "{homedir}/.tox/distshare"
else:
raise ValueError("invalid context")
if config.option.hashseed is None:
hashseed = make_hashseed()
elif config.option.hashseed == 'noset':
hashseed = None
else:
hashseed = config.option.hashseed
config.hashseed = hashseed
reader.addsubstitutions(toxinidir=config.toxinidir,
homedir=config.homedir)
config.toxworkdir = reader.getpath("toxworkdir", "{toxinidir}/.tox")
config.minversion = reader.getstring("minversion", None)
if not config.option.skip_missing_interpreters:
config.option.skip_missing_interpreters = \
reader.getbool("skip_missing_interpreters", False)
# determine indexserver dictionary
config.indexserver = {'default': IndexServerConfig('default')}
prefix = "indexserver"
for line in reader.getlist(prefix):
name, url = map(lambda x: x.strip(), line.split("=", 1))
config.indexserver[name] = IndexServerConfig(name, url)
override = False
if config.option.indexurl:
for urldef in config.option.indexurl:
m = re.match(r"\W*(\w+)=(\S+)", urldef)
if m is None:
url = urldef
name = "default"
else:
name, url = m.groups()
if not url:
url = None
if name != "ALL":
config.indexserver[name].url = url
else:
override = url
# let ALL override all existing entries
if override:
for name in config.indexserver:
config.indexserver[name] = IndexServerConfig(name, override)
reader.addsubstitutions(toxworkdir=config.toxworkdir)
config.distdir = reader.getpath("distdir", "{toxworkdir}/dist")
reader.addsubstitutions(distdir=config.distdir)
config.distshare = reader.getpath("distshare", distshare_default)
reader.addsubstitutions(distshare=config.distshare)
config.sdistsrc = reader.getpath("sdistsrc", None)
config.setupdir = reader.getpath("setupdir", "{toxinidir}")
config.logdir = config.toxworkdir.join("log")
config.envlist, all_envs = self._getenvdata(reader)
# factors used in config or predefined
known_factors = self._list_section_factors("testenv")
known_factors.update(default_factors)
known_factors.add("python")
# factors stated in config envlist
stated_envlist = reader.getstring("envlist", replace=False)
if stated_envlist:
for env in _split_env(stated_envlist):
known_factors.update(env.split('-'))
# configure testenvs
for name in all_envs:
section = testenvprefix + name
factors = set(name.split('-'))
if section in self._cfg or factors <= known_factors:
config.envconfigs[name] = \
self.make_envconfig(name, section, reader._subs, config)
all_develop = all(name in config.envconfigs
and config.envconfigs[name].usedevelop
for name in config.envlist)
config.skipsdist = reader.getbool("skipsdist", all_develop)
def _list_section_factors(self, section):
factors = set()
if section in self._cfg:
for _, value in self._cfg[section].items():
exprs = re.findall(r'^([\w{}\.,-]+)\:\s+', value, re.M)
factors.update(*mapcat(_split_factor_expr, exprs))
return factors
def make_envconfig(self, name, section, subs, config):
factors = set(name.split('-'))
reader = SectionReader(section, self._cfg, fallbacksections=["testenv"],
factors=factors)
vc = TestenvConfig(config=config, envname=name, factors=factors, reader=reader)
reader.addsubstitutions(**subs)
reader.addsubstitutions(envname=name)
for env_attr in config._testenv_attr:
atype = env_attr.type
if atype in ("bool", "path", "string", "dict", "argv", "argvlist"):
meth = getattr(reader, "get" + atype)
res = meth(env_attr.name, env_attr.default)
elif atype == "space-separated-list":
res = reader.getlist(env_attr.name, sep=" ")
elif atype == "line-list":
res = reader.getlist(env_attr.name, sep="\n")
else:
raise ValueError("unknown type %r" % (atype,))
if env_attr.postprocess:
res = env_attr.postprocess(testenv_config=vc, value=res)
setattr(vc, env_attr.name, res)
if atype == "path":
reader.addsubstitutions(**{env_attr.name: res})
if env_attr.name == "envdir":
reader.addsubstitutions(envbindir=vc.envbindir, envpython=vc.envpython,
envsitepackagesdir=vc.envsitepackagesdir)
return vc
def _getenvdata(self, reader):
envstr = self.config.option.env \
or os.environ.get("TOXENV") \
or reader.getstring("envlist", replace=False) \
or []
envlist = _split_env(envstr)
# collect section envs
all_envs = set(envlist) - set(["ALL"])
for section in self._cfg:
if section.name.startswith(testenvprefix):
all_envs.add(section.name[len(testenvprefix):])
if not all_envs:
all_envs.add("python")
if not envlist or "ALL" in envlist:
envlist = sorted(all_envs)
return envlist, all_envs
def _split_env(env):
"""if handed a list, action="append" was used for -e """
if not isinstance(env, list):
if '\n' in env:
env = ','.join(env.split('\n'))
env = [env]
return mapcat(_expand_envstr, env)
def _split_factor_expr(expr):
partial_envs = _expand_envstr(expr)
return [set(e.split('-')) for e in partial_envs]
def _expand_envstr(envstr):
# split by commas not in groups
tokens = re.split(r'((?:\{[^}]+\})+)|,', envstr)
envlist = [''.join(g).strip()
for k, g in itertools.groupby(tokens, key=bool) if k]
def expand(env):
tokens = re.split(r'\{([^}]+)\}', env)
parts = [token.split(',') for token in tokens]
return [''.join(variant) for variant in itertools.product(*parts)]
return mapcat(expand, envlist)
def mapcat(f, seq):
return list(itertools.chain.from_iterable(map(f, seq)))
class DepConfig:
def __init__(self, name, indexserver=None):
self.name = name
self.indexserver = indexserver
def __str__(self):
if self.indexserver:
if self.indexserver.name == "default":
return self.name
return ":%s:%s" % (self.indexserver.name, self.name)
return str(self.name)
__repr__ = __str__
class IndexServerConfig:
def __init__(self, name, url=None):
self.name = name
self.url = url
#: Check value matches substitution form
#: of referencing value from other section. E.g. {[base]commands}
is_section_substitution = re.compile("{\[[^{}\s]+\]\S+?}").match
RE_ITEM_REF = re.compile(
r'''
(?<!\\)[{]
(?:(?P<sub_type>[^[:{}]+):)? # optional sub_type for special rules
(?P<substitution_value>[^{}]*) # substitution key
[}]
''',
re.VERBOSE)
class SectionReader:
def __init__(self, section_name, cfgparser, fallbacksections=None, factors=()):
self.section_name = section_name
self._cfg = cfgparser
self.fallbacksections = fallbacksections or []
self.factors = factors
self._subs = {}
self._subststack = []
def addsubstitutions(self, _posargs=None, **kw):
self._subs.update(kw)
if _posargs:
self.posargs = _posargs
def getpath(self, name, defaultpath):
toxinidir = self._subs['toxinidir']
path = self.getstring(name, defaultpath)
if path is not None:
return toxinidir.join(path, abs=True)
def getlist(self, name, sep="\n"):
s = self.getstring(name, None)
if s is None:
return []
return [x.strip() for x in s.split(sep) if x.strip()]
def getdict(self, name, default=None, sep="\n"):
s = self.getstring(name, None)
if s is None:
return default or {}
value = {}
for line in s.split(sep):
if line.strip():
name, rest = line.split('=', 1)
value[name.strip()] = rest.strip()
return value
def getbool(self, name, default=None):
s = self.getstring(name, default)
if not s:
s = default
if s is None:
raise KeyError("no config value [%s] %s found" % (
self.section_name, name))
if not isinstance(s, bool):
if s.lower() == "true":
s = True
elif s.lower() == "false":
s = False
else:
raise tox.exception.ConfigError(
"boolean value %r needs to be 'True' or 'False'")
return s
def getargvlist(self, name, default=""):
s = self.getstring(name, default, replace=False)
return _ArgvlistReader.getargvlist(self, s)
def getargv(self, name, default=""):
return self.getargvlist(name, default)[0]
def getstring(self, name, default=None, replace=True):
x = None
for s in [self.section_name] + self.fallbacksections:
try:
x = self._cfg[s][name]
break
except KeyError:
continue
if x is None:
x = default
else:
x = self._apply_factors(x)
if replace and x and hasattr(x, 'replace'):
self._subststack.append((self.section_name, name))
try:
x = self._replace(x)
finally:
assert self._subststack.pop() == (self.section_name, name)
# print "getstring", self.section_name, name, "returned", repr(x)
return x
def _apply_factors(self, s):
def factor_line(line):
m = re.search(r'^([\w{}\.,-]+)\:\s+(.+)', line)
if not m:
return line
expr, line = m.groups()
if any(fs <= self.factors for fs in _split_factor_expr(expr)):
return line
lines = s.strip().splitlines()
return '\n'.join(filter(None, map(factor_line, lines)))
def _replace_env(self, match):
env_list = self.getdict('setenv')
match_value = match.group('substitution_value')
if not match_value:
raise tox.exception.ConfigError(
'env: requires an environment variable name')
default = None
envkey_split = match_value.split(':', 1)
if len(envkey_split) is 2:
envkey, default = envkey_split
else:
envkey = match_value
if envkey not in os.environ and default is None:
if envkey not in env_list and default is None:
raise tox.exception.ConfigError(
"substitution env:%r: unknown environment variable %r" %
(envkey, envkey))
if envkey in os.environ:
return os.environ.get(envkey, default)
else:
return env_list.get(envkey, default)
def _substitute_from_other_section(self, key):
if key.startswith("[") and "]" in key:
i = key.find("]")
section, item = key[1:i], key[i + 1:]
if section in self._cfg and item in self._cfg[section]:
if (section, item) in self._subststack:
raise ValueError('%s already in %s' % (
(section, item), self._subststack))
x = str(self._cfg[section][item])
self._subststack.append((section, item))
try:
return self._replace(x)
finally:
self._subststack.pop()
raise tox.exception.ConfigError(
"substitution key %r not found" % key)
def _replace_substitution(self, match):
sub_key = match.group('substitution_value')
val = self._subs.get(sub_key, None)
if val is None:
val = self._substitute_from_other_section(sub_key)
if py.builtin.callable(val):
val = val()
return str(val)
def _replace_match(self, match):
g = match.groupdict()
# special case: opts and packages. Leave {opts} and
# {packages} intact, they are replaced manually in
# _venv.VirtualEnv.run_install_command.
sub_value = g['substitution_value']
if sub_value in ('opts', 'packages'):
return '{%s}' % sub_value
handlers = {
'env': self._replace_env,
None: self._replace_substitution,
}
try:
sub_type = g['sub_type']
except KeyError:
raise tox.exception.ConfigError(
"Malformed substitution; no substitution type provided")
try:
handler = handlers[sub_type]
except KeyError:
raise tox.exception.ConfigError("No support for the %s substitution type" % sub_type)
return handler(match)
def _replace(self, x):
if '{' in x:
return RE_ITEM_REF.sub(self._replace_match, x)
return x
class _ArgvlistReader:
@classmethod
def getargvlist(cls, reader, value):
"""Parse ``commands`` argvlist multiline string.
:param str name: Key name in a section.
:param str value: Content stored by key.
:rtype: list[list[str]]
:raise :class:`tox.exception.ConfigError`:
line-continuation ends nowhere while resolving for specified section
"""
commands = []
current_command = ""
for line in value.splitlines():
line = line.rstrip()
i = line.find("#")
if i != -1:
line = line[:i].rstrip()
if not line:
continue
if line.endswith("\\"):
current_command += " " + line[:-1]
continue
current_command += line
if is_section_substitution(current_command):
replaced = reader._replace(current_command)
commands.extend(cls.getargvlist(reader, replaced))
else:
commands.append(cls.processcommand(reader, current_command))
current_command = ""
else:
if current_command:
raise tox.exception.ConfigError(
"line-continuation ends nowhere while resolving for [%s] %s" %
(reader.section_name, "commands"))
return commands
@classmethod
def processcommand(cls, reader, command):
posargs = getattr(reader, "posargs", None)
# Iterate through each word of the command substituting as
# appropriate to construct the new command string. This
# string is then broken up into exec argv components using
# shlex.
newcommand = ""
for word in CommandParser(command).words():
if word == "{posargs}" or word == "[]":
if posargs:
newcommand += " ".join(posargs)
continue
elif word.startswith("{posargs:") and word.endswith("}"):
if posargs:
newcommand += " ".join(posargs)
continue
else:
word = word[9:-1]
new_arg = ""
new_word = reader._replace(word)
new_word = reader._replace(new_word)
new_arg += new_word
newcommand += new_arg
# Construct shlex object that will not escape any values,
# use all values as is in argv.
shlexer = shlex.shlex(newcommand, posix=True)
shlexer.whitespace_split = True
shlexer.escape = ''
shlexer.commenters = ''
argv = list(shlexer)
return argv
class CommandParser(object):
class State(object):
def __init__(self):
self.word = ''
self.depth = 0
self.yield_words = []
def __init__(self, command):
self.command = command
def words(self):
ps = CommandParser.State()
def word_has_ended():
return ((cur_char in string.whitespace and ps.word and
ps.word[-1] not in string.whitespace) or
(cur_char == '{' and ps.depth == 0 and not ps.word.endswith('\\')) or
(ps.depth == 0 and ps.word and ps.word[-1] == '}') or
(cur_char not in string.whitespace and ps.word and
ps.word.strip() == ''))
def yield_this_word():
yieldword = ps.word
ps.word = ''
if yieldword:
ps.yield_words.append(yieldword)
def yield_if_word_ended():
if word_has_ended():
yield_this_word()
def accumulate():
ps.word += cur_char
def push_substitution():
ps.depth += 1
def pop_substitution():
ps.depth -= 1
for cur_char in self.command:
if cur_char in string.whitespace:
if ps.depth == 0:
yield_if_word_ended()
accumulate()
elif cur_char == '{':
yield_if_word_ended()
accumulate()
push_substitution()
elif cur_char == '}':
accumulate()
pop_substitution()
else:
yield_if_word_ended()
accumulate()
if ps.word.strip():
yield_this_word()
return ps.yield_words
def getcontextname():
if any(env in os.environ for env in ['JENKINS_URL', 'HUDSON_URL']):
return 'jenkins'
return None
|