/
configtypes.py
1544 lines (1223 loc) · 47.4 KB
/
configtypes.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
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Setting options used for qutebrowser."""
import re
import json
import shlex
import base64
import codecs
import os.path
import itertools
import collections
import warnings
import datetime
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtNetwork import QNetworkProxy
from PyQt5.QtWidgets import QTabWidget, QTabBar
from qutebrowser.commands import cmdutils
from qutebrowser.config import configexc
from qutebrowser.utils import standarddir, utils
SYSTEM_PROXY = object() # Return value for Proxy type
# Taken from configparser
BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
def _validate_regex(pattern, flags):
"""Check if the given regex is valid.
This is more complicated than it could be since there's a warning on
invalid escapes with newer Python versions, and we want to catch that case
and treat it as invalid.
"""
with warnings.catch_warnings(record=True) as recorded_warnings:
warnings.simplefilter('always')
try:
re.compile(pattern, flags)
except re.error as e:
raise configexc.ValidationError(
pattern, "must be a valid regex - " + str(e))
except RuntimeError:
raise configexc.ValidationError(
pattern, "must be a valid regex - recursion depth exceeded")
for w in recorded_warnings:
if (issubclass(w.category, DeprecationWarning) and
str(w.message).startswith('bad escape')):
raise configexc.ValidationError(
pattern, "must be a valid regex - " + str(w.message))
else:
warnings.warn(w.message)
class ValidValues:
"""Container for valid values for a given type.
Attributes:
values: A list with the allowed untransformed values.
descriptions: A dict with value/desc mappings.
"""
def __init__(self, *vals):
if not vals:
raise ValueError("ValidValues with no values makes no sense!")
self.descriptions = {}
self.values = []
for v in vals:
if isinstance(v, str):
# Value without description
self.values.append(v)
else:
# (value, description) tuple
self.values.append(v[0])
self.descriptions[v[0]] = v[1]
def __contains__(self, val):
return val in self.values
def __iter__(self):
return self.values.__iter__()
def __repr__(self):
return utils.get_repr(self, values=self.values,
descriptions=self.descriptions)
class BaseType:
"""A type used for a setting value.
Attributes:
none_ok: Whether to convert to None for an empty string.
Class attributes:
valid_values: Possible values if they can be expressed as a fixed
string. ValidValues instance.
"""
def __init__(self, none_ok=False):
self.none_ok = none_ok
self.valid_values = None
def get_name(self):
"""Get a name for the type for documentation."""
return self.__class__.__name__
def get_valid_values(self):
"""Get the type's valid values for documentation."""
return self.valid_values
def _basic_validation(self, value):
"""Do some basic validation for the value (empty, non-printable chars).
Arguments:
value: The value to check.
"""
if not value:
if self.none_ok:
return
else:
raise configexc.ValidationError(value, "may not be empty!")
if any(ord(c) < 32 or ord(c) == 0x7f for c in value):
raise configexc.ValidationError(value, "may not contain "
"unprintable chars!")
def transform(self, value):
"""Transform the setting value.
This method can assume the value is indeed a valid value.
The default implementation returns the original value.
Args:
value: The original string value.
Return:
The transformed value.
"""
if not value:
return None
else:
return value
def validate(self, value):
"""Validate value against possible values.
The default implementation checks the value against self.valid_values
if it was defined.
Args:
value: The value to validate.
"""
self._basic_validation(value)
if not value:
return
if self.valid_values is not None:
if value not in self.valid_values:
raise configexc.ValidationError(
value,
"valid values: {}".format(', '.join(self.valid_values)))
else:
raise NotImplementedError("{} does not implement validate.".format(
self.__class__.__name__))
def complete(self):
"""Return a list of possible values for completion.
The default implementation just returns valid_values, but it might be
useful to override this for special cases.
Return:
A list of (value, description) tuples or None.
"""
if self.valid_values is None:
return None
else:
out = []
for val in self.valid_values:
try:
desc = self.valid_values.descriptions[val]
except KeyError:
# Some values are self-explaining and don't need a
# description.
desc = ""
out.append((val, desc))
return out
class MappingType(BaseType):
"""Base class for any setting which has a mapping to the given values.
Attributes:
MAPPING: The mapping to use.
"""
MAPPING = {}
def __init__(self, none_ok=False,
valid_values=None):
super().__init__(none_ok)
self.valid_values = valid_values
def validate(self, value):
super().validate(value.lower())
def transform(self, value):
if not value:
return None
return self.MAPPING[value.lower()]
class String(BaseType):
"""Base class for a string setting (case-insensitive).
Attributes:
minlen: Minimum length (inclusive).
maxlen: Maximum length (inclusive).
forbidden: Forbidden chars in the string.
_completions: completions to be used, or None
"""
def __init__(self, minlen=None, maxlen=None, forbidden=None,
none_ok=False, completions=None, valid_values=None):
super().__init__(none_ok)
self.valid_values = valid_values
if minlen is not None and minlen < 1:
raise ValueError("minlen ({}) needs to be >= 1!".format(minlen))
elif maxlen is not None and maxlen < 1:
raise ValueError("maxlen ({}) needs to be >= 1!".format(maxlen))
elif maxlen is not None and minlen is not None and maxlen < minlen:
raise ValueError("minlen ({}) needs to be <= maxlen ({})!".format(
minlen, maxlen))
self.minlen = minlen
self.maxlen = maxlen
self.forbidden = forbidden
self._completions = completions
def validate(self, value):
self._basic_validation(value)
if not value:
return
if self.valid_values is not None:
if value not in self.valid_values:
raise configexc.ValidationError(
value,
"valid values: {}".format(', '.join(self.valid_values)))
if self.forbidden is not None and any(c in value
for c in self.forbidden):
raise configexc.ValidationError(value, "may not contain the chars "
"'{}'".format(self.forbidden))
if self.minlen is not None and len(value) < self.minlen:
raise configexc.ValidationError(value, "must be at least {} chars "
"long!".format(self.minlen))
if self.maxlen is not None and len(value) > self.maxlen:
raise configexc.ValidationError(value, "must be at most {} chars "
"long!".format(self.maxlen))
def complete(self):
if self._completions is not None:
return self._completions
else:
return super().complete()
class UniqueCharString(String):
"""A string which may not contain duplicate chars."""
def validate(self, value):
super().validate(value)
if not value:
return
# Check for duplicate values
if len(set(value)) != len(value):
raise configexc.ValidationError(
value, "String contains duplicate values!")
class List(BaseType):
"""Base class for a (string-)list setting."""
_show_inner_type = True
def __init__(self, inner_type, none_ok=False, length=None):
super().__init__(none_ok)
self.inner_type = inner_type
self.length = length
def get_name(self):
name = super().get_name()
if self._show_inner_type:
name += " of " + self.inner_type.get_name()
return name
def get_valid_values(self):
return self.inner_type.get_valid_values()
def transform(self, value):
if not value:
return None
else:
return [self.inner_type.transform(v.strip())
for v in value.split(',')]
def validate(self, value):
self._basic_validation(value)
if not value:
return
vals = value.split(',')
if self.length is not None and len(vals) != self.length:
raise configexc.ValidationError(value, "Exactly {} values need to "
"be set!".format(self.length))
for val in vals:
self.inner_type.validate(val.strip())
class FlagList(List):
"""Base class for a list setting that contains one or more flags.
Lists with duplicate flags are invalid and each item is checked against
self.valid_values (if not empty).
"""
combinable_values = None
_show_inner_type = False
def __init__(self, none_ok=False, valid_values=None):
super().__init__(BaseType(), none_ok)
self.inner_type.valid_values = valid_values
def validate(self, value):
if self.inner_type.valid_values is not None:
super().validate(value)
else:
self._basic_validation(value)
if not value:
return
vals = super().transform(value)
# Check for duplicate values
if len(set(vals)) != len(vals):
raise configexc.ValidationError(
value, "List contains duplicate values!")
def complete(self):
valid_values = self.inner_type.valid_values
if valid_values is None:
return None
out = []
# Single value completions
for value in valid_values:
desc = valid_values.descriptions.get(value, "")
out.append((value, desc))
combinables = self.combinable_values
if combinables is None:
combinables = list(valid_values)
# Generate combinations of each possible value combination
for size in range(2, len(combinables) + 1):
for combination in itertools.combinations(combinables, size):
out.append((','.join(combination), ''))
return out
class Bool(BaseType):
"""Base class for a boolean setting."""
def __init__(self, none_ok=False):
super().__init__(none_ok)
self.valid_values = ValidValues('true', 'false')
def transform(self, value):
if not value:
return None
else:
return BOOLEAN_STATES[value.lower()]
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif value.lower() not in BOOLEAN_STATES:
raise configexc.ValidationError(value, "must be a boolean!")
class BoolAsk(Bool):
"""A yes/no/ask question."""
def __init__(self, none_ok=False):
super().__init__(none_ok)
self.valid_values = ValidValues('true', 'false', 'ask')
def transform(self, value):
if value.lower() == 'ask':
return 'ask'
else:
return super().transform(value)
def validate(self, value):
if value.lower() == 'ask':
return
else:
super().validate(value)
class Int(BaseType):
"""Base class for an integer setting.
Attributes:
minval: Minimum value (inclusive).
maxval: Maximum value (inclusive).
"""
def __init__(self, minval=None, maxval=None, none_ok=False):
super().__init__(none_ok)
if maxval is not None and minval is not None and maxval < minval:
raise ValueError("minval ({}) needs to be <= maxval ({})!".format(
minval, maxval))
self.minval = minval
self.maxval = maxval
def transform(self, value):
if not value:
return None
else:
return int(value)
def validate(self, value):
self._basic_validation(value)
if not value:
return
try:
intval = int(value)
except ValueError:
raise configexc.ValidationError(value, "must be an integer!")
if self.minval is not None and intval < self.minval:
raise configexc.ValidationError(value, "must be {} or "
"bigger!".format(self.minval))
if self.maxval is not None and intval > self.maxval:
raise configexc.ValidationError(value, "must be {} or "
"smaller!".format(self.maxval))
class Float(BaseType):
"""Base class for a float setting.
Attributes:
minval: Minimum value (inclusive).
maxval: Maximum value (inclusive).
"""
def __init__(self, minval=None, maxval=None, none_ok=False):
super().__init__(none_ok)
if maxval is not None and minval is not None and maxval < minval:
raise ValueError("minval ({}) needs to be <= maxval ({})!".format(
minval, maxval))
self.minval = minval
self.maxval = maxval
def transform(self, value):
if not value:
return None
else:
return float(value)
def validate(self, value):
self._basic_validation(value)
if not value:
return
try:
floatval = float(value)
except ValueError:
raise configexc.ValidationError(value, "must be a float!")
if self.minval is not None and floatval < self.minval:
raise configexc.ValidationError(value, "must be {} or "
"bigger!".format(self.minval))
if self.maxval is not None and floatval > self.maxval:
raise configexc.ValidationError(value, "must be {} or "
"smaller!".format(self.maxval))
class Perc(BaseType):
"""Percentage.
Attributes:
minval: Minimum value (inclusive).
maxval: Maximum value (inclusive).
"""
def __init__(self, minval=None, maxval=None, none_ok=False):
super().__init__(none_ok)
if maxval is not None and minval is not None and maxval < minval:
raise ValueError("minval ({}) needs to be <= maxval ({})!".format(
minval, maxval))
self.minval = minval
self.maxval = maxval
def transform(self, value):
if not value:
return
else:
return int(value[:-1])
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif not value.endswith('%'):
raise configexc.ValidationError(value, "does not end with %")
try:
intval = int(value[:-1])
except ValueError:
raise configexc.ValidationError(value, "invalid percentage!")
if self.minval is not None and intval < self.minval:
raise configexc.ValidationError(value, "must be {}% or "
"more!".format(self.minval))
if self.maxval is not None and intval > self.maxval:
raise configexc.ValidationError(value, "must be {}% or "
"less!".format(self.maxval))
class PercOrInt(BaseType):
"""Percentage or integer.
Attributes:
minperc: Minimum value for percentage (inclusive).
maxperc: Maximum value for percentage (inclusive).
minint: Minimum value for integer (inclusive).
maxint: Maximum value for integer (inclusive).
"""
def __init__(self, minperc=None, maxperc=None, minint=None, maxint=None,
none_ok=False):
super().__init__(none_ok)
if maxint is not None and minint is not None and maxint < minint:
raise ValueError("minint ({}) needs to be <= maxint ({})!".format(
minint, maxint))
if maxperc is not None and minperc is not None and maxperc < minperc:
raise ValueError("minperc ({}) needs to be <= maxperc "
"({})!".format(minperc, maxperc))
self.minperc = minperc
self.maxperc = maxperc
self.minint = minint
self.maxint = maxint
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif value.endswith('%'):
try:
intval = int(value[:-1])
except ValueError:
raise configexc.ValidationError(value, "invalid percentage!")
if self.minperc is not None and intval < self.minperc:
raise configexc.ValidationError(value, "must be {}% or "
"more!".format(self.minperc))
if self.maxperc is not None and intval > self.maxperc:
raise configexc.ValidationError(value, "must be {}% or "
"less!".format(self.maxperc))
else:
try:
intval = int(value)
except ValueError:
raise configexc.ValidationError(value, "must be integer or "
"percentage!")
if self.minint is not None and intval < self.minint:
raise configexc.ValidationError(value, "must be {} or "
"bigger!".format(self.minint))
if self.maxint is not None and intval > self.maxint:
raise configexc.ValidationError(value, "must be {} or "
"smaller!".format(self.maxint))
class Command(BaseType):
"""Base class for a command value with arguments."""
def validate(self, value):
self._basic_validation(value)
if not value:
return
split = value.split()
if not split or split[0] not in cmdutils.cmd_dict:
raise configexc.ValidationError(value, "must be a valid command!")
def complete(self):
out = []
for cmdname, obj in cmdutils.cmd_dict.items():
out.append((cmdname, obj.desc))
return out
class ColorSystem(MappingType):
"""Color systems for interpolation."""
def __init__(self, none_ok=False):
super().__init__(
none_ok,
valid_values=ValidValues(
('rgb', "Interpolate in the RGB color system."),
('hsv', "Interpolate in the HSV color system."),
('hsl', "Interpolate in the HSL color system."),
('none', "Don't show a gradient.")))
MAPPING = {
'rgb': QColor.Rgb,
'hsv': QColor.Hsv,
'hsl': QColor.Hsl,
'none': None,
}
class QtColor(BaseType):
"""Base class for QColor."""
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif QColor.isValidColor(value):
pass
else:
raise configexc.ValidationError(value, "must be a valid color")
def transform(self, value):
if not value:
return None
else:
return QColor(value)
class CssColor(BaseType):
"""Base class for a CSS color value."""
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif value.startswith('-'):
# custom function name, won't validate.
pass
elif QColor.isValidColor(value):
pass
else:
raise configexc.ValidationError(value, "must be a valid color")
class QssColor(CssColor):
"""Base class for a color value.
Class attributes:
color_func_regexes: Valid function regexes.
"""
num = r'[0-9]{1,3}%?'
color_func_regexes = [
r'rgb\({num},\s*{num},\s*{num}\)'.format(num=num),
r'rgba\({num},\s*{num},\s*{num},\s*{num}\)'.format(num=num),
r'hsv\({num},\s*{num},\s*{num}\)'.format(num=num),
r'hsva\({num},\s*{num},\s*{num},\s*{num}\)'.format(num=num),
r'qlineargradient\(.*\)',
r'qradialgradient\(.*\)',
r'qconicalgradient\(.*\)',
]
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif any(re.match(r, value) for r in self.color_func_regexes):
# QColor doesn't handle these, so we do the best we can easily
pass
elif QColor.isValidColor(value):
pass
else:
raise configexc.ValidationError(value, "must be a valid color")
class Font(BaseType):
"""Base class for a font value."""
font_regex = re.compile(r"""
^(
(
# style
(?P<style>normal|italic|oblique) |
# weight (named | 100..900)
(
(?P<weight>[123456789]00) |
(?P<namedweight>normal|bold)
) |
# size (<float>pt | <int>px)
(?P<size>[0-9]+((\.[0-9]+)?[pP][tT]|[pP][xX]))
)\ # size/weight/style are space-separated
)* # 0-inf size/weight/style tags
(?P<family>[A-Za-z0-9, "-]*)$ # mandatory font family""", re.VERBOSE)
def validate(self, value):
self._basic_validation(value)
if not value:
return
elif not self.font_regex.match(value):
raise configexc.ValidationError(value, "must be a valid font")
class FontFamily(Font):
"""A Qt font family."""
def validate(self, value):
self._basic_validation(value)
if not value:
return
match = self.font_regex.match(value)
if not match:
raise configexc.ValidationError(value, "must be a valid font")
for group in 'style', 'weight', 'namedweight', 'size':
if match.group(group):
raise configexc.ValidationError(value, "may not include a "
"{}!".format(group))
class QtFont(Font):
"""A Font which gets converted to a QFont."""
def transform(self, value):
if not value:
return None
style_map = {
'normal': QFont.StyleNormal,
'italic': QFont.StyleItalic,
'oblique': QFont.StyleOblique,
}
weight_map = {
'normal': QFont.Normal,
'bold': QFont.Bold,
}
font = QFont()
font.setStyle(QFont.StyleNormal)
font.setWeight(QFont.Normal)
match = self.font_regex.match(value)
style = match.group('style')
weight = match.group('weight')
namedweight = match.group('namedweight')
size = match.group('size')
family = match.group('family')
if style:
font.setStyle(style_map[style])
if namedweight:
font.setWeight(weight_map[namedweight])
if weight:
# based on qcssparser.cpp:setFontWeightFromValue
font.setWeight(min(int(weight) / 8, 99))
if size:
if size.lower().endswith('pt'):
font.setPointSizeF(float(size[:-2]))
elif size.lower().endswith('px'):
font.setPixelSize(int(size[:-2]))
else:
# This should never happen as the regex only lets pt/px
# through.
raise ValueError("Unexpected size unit in {!r}!".format(
size)) # pragma: no cover
# The Qt CSS parser handles " and ' before passing the string to
# QFont.setFamily. We could do proper CSS-like parsing here, but since
# hopefully nobody will ever have a font with quotes in the family (if
# that's even possible), we take a much more naive approach.
family = family.replace('"', '').replace("'", '')
font.setFamily(family)
return font
class Regex(BaseType):
"""A regular expression."""
def __init__(self, flags=0, none_ok=False):
super().__init__(none_ok)
self.flags = flags
def validate(self, value):
self._basic_validation(value)
if not value:
return
_validate_regex(value, self.flags)
def transform(self, value):
if not value:
return None
else:
return re.compile(value, self.flags)
class File(BaseType):
"""A file on the local filesystem."""
def __init__(self, required=True, **kwargs):
super().__init__(**kwargs)
self.required = required
def transform(self, value):
if not value:
return None
value = os.path.expanduser(value)
value = os.path.expandvars(value)
if not os.path.isabs(value):
cfgdir = standarddir.config()
assert cfgdir is not None
value = os.path.join(cfgdir, value)
return value
def validate(self, value):
self._basic_validation(value)
if not value:
return
value = os.path.expanduser(value)
value = os.path.expandvars(value)
try:
if not os.path.isabs(value):
cfgdir = standarddir.config()
if cfgdir is None:
raise configexc.ValidationError(
value, "must be an absolute path when not using a "
"config directory!")
value = os.path.join(cfgdir, value)
not_isfile_message = ("must be a valid path relative to the "
"config directory!")
else:
not_isfile_message = "must be a valid file!"
if self.required and not os.path.isfile(value):
raise configexc.ValidationError(value, not_isfile_message)
except UnicodeEncodeError as e:
raise configexc.ValidationError(value, e)
class Directory(BaseType):
"""A directory on the local filesystem."""
def validate(self, value):
self._basic_validation(value)
if not value:
return
value = os.path.expandvars(value)
value = os.path.expanduser(value)
try:
if not os.path.isdir(value):
raise configexc.ValidationError(
value, "must be a valid directory!")
if not os.path.isabs(value):
raise configexc.ValidationError(
value, "must be an absolute path!")
except UnicodeEncodeError as e:
raise configexc.ValidationError(value, e)
def transform(self, value):
if not value:
return None
value = os.path.expandvars(value)
return os.path.expanduser(value)
class FormatString(BaseType):
"""A string with '{foo}'-placeholders."""
def __init__(self, fields, none_ok=False):
super().__init__(none_ok)
self.fields = fields
def validate(self, value):
self._basic_validation(value)
if not value:
return
s = self.transform(value)
try:
return s.format(**{k: '' for k in self.fields})
except (KeyError, IndexError) as e:
raise configexc.ValidationError(value, "Invalid placeholder "
"{}".format(e))
except ValueError as e:
raise configexc.ValidationError(value, str(e))
class WebKitBytes(BaseType):
"""A size with an optional suffix.
Attributes:
maxsize: The maximum size to be used.
Class attributes:
SUFFIXES: A mapping of size suffixes to multiplicators.
"""
SUFFIXES = {
'k': 1024 ** 1,
'm': 1024 ** 2,
'g': 1024 ** 3,
't': 1024 ** 4,
'p': 1024 ** 5,
'e': 1024 ** 6,
'z': 1024 ** 7,
'y': 1024 ** 8,
}
def __init__(self, maxsize=None, none_ok=False):
super().__init__(none_ok)
self.maxsize = maxsize
def validate(self, value):
self._basic_validation(value)
if not value:
return
try:
val = self.transform(value)
except ValueError:
raise configexc.ValidationError(value, "must be a valid integer "
"with optional suffix!")
if self.maxsize is not None and val > self.maxsize:
raise configexc.ValidationError(value, "must be {} "
"maximum!".format(self.maxsize))
if val < 0:
raise configexc.ValidationError(value, "must be 0 minimum!")
def transform(self, value):
if not value:
return None
elif any(value.lower().endswith(c) for c in self.SUFFIXES):
suffix = value[-1].lower()
val = value[:-1]
multiplicator = self.SUFFIXES[suffix]
else:
val = value
multiplicator = 1
return int(val) * multiplicator
class ShellCommand(BaseType):
"""A shellcommand which is split via shlex.
Attributes:
placeholder: If there should be a placeholder.
"""
def __init__(self, placeholder=False, none_ok=False):
super().__init__(none_ok)
self.placeholder = placeholder