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
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
|
# deps.py -- Portage dependency resolution functions
# Copyright 2003-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id$
# DEPEND SYNTAX:
#
# 'use?' only affects the immediately following word!
# Nesting is the only legal way to form multiple '[!]use?' requirements.
#
# Where: 'a' and 'b' are use flags, and 'z' is a depend atom.
#
# "a? z" -- If 'a' in [use], then b is valid.
# "a? ( z )" -- Syntax with parenthesis.
# "a? b? z" -- Deprecated.
# "a? ( b? z )" -- Valid
# "a? ( b? ( z ) ) -- Valid
#
import re, sys
import weakref
from itertools import chain
import portage.exception
from portage.exception import InvalidData, InvalidAtom
from portage.localization import _
from portage.versions import catpkgsplit, catsplit, \
pkgcmp, pkgsplit, ververify, _version
import portage.cache.mappings
def cpvequal(cpv1, cpv2):
"""
@param cpv1: CategoryPackageVersion (no operators) Example: "sys-apps/portage-2.1"
@type cpv1: String
@param cpv2: CategoryPackageVersion (no operators) Example: "sys-apps/portage-2.1"
@type cpv2: String
@rtype: Boolean
@returns:
1. True if cpv1 = cpv2
2. False Otherwise
3. Throws PortageException if cpv1 or cpv2 is not a CPV
Example Usage:
>>> from portage.dep import cpvequal
>>> cpvequal("sys-apps/portage-2.1","sys-apps/portage-2.1")
>>> True
"""
split1 = catpkgsplit(cpv1)
split2 = catpkgsplit(cpv2)
if not split1 or not split2:
raise portage.exception.PortageException(_("Invalid data '%s, %s', parameter was not a CPV") % (cpv1, cpv2))
if split1[0] != split2[0]:
return False
return (pkgcmp(split1[1:], split2[1:]) == 0)
def strip_empty(myarr):
"""
Strip all empty elements from an array
@param myarr: The list of elements
@type myarr: List
@rtype: Array
@return: The array with empty elements removed
"""
return [x for x in myarr if x]
_paren_whitespace_re = re.compile(r'\S(\(|\))|(\(|\))\S')
def paren_reduce(mystr,tokenize=1):
"""
Take a string and convert all paren enclosed entities into sublists, optionally
futher splitting the list elements by spaces.
Example usage:
>>> paren_reduce('foobar foo ( bar baz )',1)
['foobar', 'foo', ['bar', 'baz']]
>>> paren_reduce('foobar foo ( bar baz )',0)
['foobar foo ', [' bar baz ']]
@param mystr: The string to reduce
@type mystr: String
@param tokenize: Split on spaces to produces further list breakdown
@type tokenize: Integer
@rtype: Array
@return: The reduced string in an array
"""
global _dep_check_strict, _paren_whitespace_re
if _dep_check_strict:
m = _paren_whitespace_re.search(mystr)
if m is not None:
raise portage.exception.InvalidDependString(
_("missing space by parenthesis: '%s'") % m.group(0))
mylist = []
while mystr:
left_paren = mystr.find("(")
has_left_paren = left_paren != -1
right_paren = mystr.find(")")
has_right_paren = right_paren != -1
if not has_left_paren and not has_right_paren:
freesec = mystr
subsec = None
tail = ""
elif mystr[0] == ")":
return [mylist,mystr[1:]]
elif has_left_paren and not has_right_paren:
raise portage.exception.InvalidDependString(
_("missing right parenthesis: '%s'") % mystr)
elif has_left_paren and left_paren < right_paren:
freesec,subsec = mystr.split("(",1)
sublist = paren_reduce(subsec, tokenize=tokenize)
if len(sublist) != 2:
raise portage.exception.InvalidDependString(
_("malformed syntax: '%s'") % mystr)
subsec, tail = sublist
else:
subsec,tail = mystr.split(")",1)
if tokenize:
subsec = strip_empty(subsec.split(" "))
return [mylist+subsec,tail]
return mylist+[subsec],tail
if not isinstance(tail, basestring):
raise portage.exception.InvalidDependString(
_("malformed syntax: '%s'") % mystr)
mystr = tail
if freesec:
if tokenize:
mylist = mylist + strip_empty(freesec.split(" "))
else:
mylist = mylist + [freesec]
if subsec is not None:
mylist = mylist + [subsec]
return mylist
class paren_normalize(list):
"""Take a dependency structure as returned by paren_reduce or use_reduce
and generate an equivalent structure that has no redundant lists."""
def __init__(self, src):
list.__init__(self)
self._zap_parens(src, self)
def _zap_parens(self, src, dest, disjunction=False):
if not src:
return dest
i = iter(src)
for x in i:
if isinstance(x, basestring):
if x == '||':
x = self._zap_parens(i.next(), [], disjunction=True)
if len(x) == 1:
dest.append(x[0])
else:
dest.append("||")
dest.append(x)
elif x.endswith("?"):
dest.append(x)
dest.append(self._zap_parens(i.next(), []))
else:
dest.append(x)
else:
if disjunction:
x = self._zap_parens(x, [])
if len(x) == 1:
dest.append(x[0])
else:
dest.append(x)
else:
self._zap_parens(x, dest)
return dest
def paren_enclose(mylist):
"""
Convert a list to a string with sublists enclosed with parens.
Example usage:
>>> test = ['foobar','foo',['bar','baz']]
>>> paren_enclose(test)
'foobar foo ( bar baz )'
@param mylist: The list
@type mylist: List
@rtype: String
@return: The paren enclosed string
"""
mystrparts = []
for x in mylist:
if isinstance(x, list):
mystrparts.append("( "+paren_enclose(x)+" )")
else:
mystrparts.append(x)
return " ".join(mystrparts)
# This is just for use by emerge so that it can enable a backward compatibility
# mode in order to gracefully deal with installed packages that have invalid
# atoms or dep syntax. For backward compatibility with api consumers, strict
# behavior will be explicitly enabled as necessary.
_dep_check_strict = False
def use_reduce(deparray, uselist=[], masklist=[], matchall=0, excludeall=[]):
"""
Takes a paren_reduce'd array and reduces the use? conditionals out
leaving an array with subarrays
@param deparray: paren_reduce'd list of deps
@type deparray: List
@param uselist: List of use flags
@type uselist: List
@param masklist: List of masked flags
@type masklist: List
@param matchall: Resolve all conditional deps unconditionally. Used by repoman
@type matchall: Integer
@rtype: List
@return: The use reduced depend array
"""
# Quick validity checks
for x, y in enumerate(deparray):
if y == '||':
if len(deparray) - 1 == x or not isinstance(deparray[x+1], list):
raise portage.exception.InvalidDependString(_('%(dep)s missing atom list in "%(deparray)s"') % {"dep": deparray[x], "deparray": paren_enclose(deparray)})
if deparray and deparray[-1] and deparray[-1][-1] == "?":
raise portage.exception.InvalidDependString(_('Conditional without target in "%s"') % paren_enclose(deparray))
global _dep_check_strict
mydeparray = deparray[:]
rlist = []
while mydeparray:
head = mydeparray.pop(0)
if not isinstance(head, basestring):
additions = use_reduce(head, uselist, masklist, matchall, excludeall)
if additions:
rlist.append(additions)
elif rlist and rlist[-1] == "||":
#XXX: Currently some DEPEND strings have || lists without default atoms.
# raise portage.exception.InvalidDependString("No default atom(s) in \""+paren_enclose(deparray)+"\"")
rlist.append([])
else:
if head[-1:] == "?": # Use reduce next group on fail.
# Pull any other use conditions and the following atom or list into a separate array
newdeparray = [head]
while isinstance(newdeparray[-1], basestring) and \
newdeparray[-1][-1:] == "?":
if mydeparray:
newdeparray.append(mydeparray.pop(0))
else:
raise ValueError(_("Conditional with no target."))
# Deprecation checks
warned = 0
if len(newdeparray[-1]) == 0:
sys.stderr.write(_("Note: Empty target in string. (Deprecated)\n"))
warned = 1
if len(newdeparray) != 2:
sys.stderr.write(_("Note: Nested use flags without parenthesis (Deprecated)\n"))
warned = 1
if warned:
sys.stderr.write(" --> "+" ".join(map(str,[head]+newdeparray))+"\n")
# Check that each flag matches
ismatch = True
missing_flag = False
for head in newdeparray[:-1]:
head = head[:-1]
if not head:
missing_flag = True
break
if head.startswith("!"):
head_key = head[1:]
if not head_key:
missing_flag = True
break
if not matchall and head_key in uselist or \
head_key in excludeall:
ismatch = False
break
elif head not in masklist:
if not matchall and head not in uselist:
ismatch = False
break
else:
ismatch = False
if missing_flag:
raise portage.exception.InvalidDependString(
_('Conditional without flag: "') + \
paren_enclose([head+"?", newdeparray[-1]])+"\"")
# If they all match, process the target
if ismatch:
target = newdeparray[-1]
if isinstance(target, list):
additions = use_reduce(target, uselist, masklist, matchall, excludeall)
if additions:
rlist.append(additions)
elif not _dep_check_strict:
# The old deprecated behavior.
rlist.append(target)
else:
raise portage.exception.InvalidDependString(
_("Conditional without parenthesis: '%s?'") % head)
else:
rlist += [head]
return rlist
def dep_opconvert(deplist):
"""
Iterate recursively through a list of deps, if the
dep is a '||' or '&&' operator, combine it with the
list of deps that follows..
Example usage:
>>> test = ["blah", "||", ["foo", "bar", "baz"]]
>>> dep_opconvert(test)
['blah', ['||', 'foo', 'bar', 'baz']]
@param deplist: A list of deps to format
@type mydep: List
@rtype: List
@return:
The new list with the new ordering
"""
retlist = []
x = 0
while x != len(deplist):
if isinstance(deplist[x], list):
retlist.append(dep_opconvert(deplist[x]))
elif deplist[x] == "||" or deplist[x] == "&&":
retlist.append([deplist[x]] + dep_opconvert(deplist[x+1]))
x += 1
else:
retlist.append(deplist[x])
x += 1
return retlist
class _use_dep(object):
__slots__ = ("__weakref__", "conditional",
"disabled", "enabled", "tokens", "required")
_conditionals_class = portage.cache.mappings.slot_dict_class(
("disabled", "enabled", "equal", "not_equal"), prefix="")
_valid_use_re = re.compile(r'^[^-?!=][^?!=]*$')
def __init__(self, use):
enabled_flags = []
disabled_flags = []
conditional = self._conditionals_class()
for k in conditional.allowed_keys:
conditional[k] = []
for x in use:
last_char = x[-1:]
first_char = x[:1]
if "?" == last_char:
if "!" == first_char:
conditional.disabled.append(
self._validate_flag(x, x[1:-1]))
else:
conditional.enabled.append(
self._validate_flag(x, x[:-1]))
elif "=" == last_char:
if "!" == first_char:
conditional.not_equal.append(
self._validate_flag(x, x[1:-1]))
else:
conditional.equal.append(
self._validate_flag(x, x[:-1]))
else:
if "-" == first_char:
disabled_flags.append(self._validate_flag(x, x[1:]))
else:
enabled_flags.append(self._validate_flag(x, x))
self.tokens = use
if not isinstance(self.tokens, tuple):
self.tokens = tuple(self.tokens)
self.required = frozenset(chain(
enabled_flags,
disabled_flags,
*conditional.values()
))
self.enabled = frozenset(enabled_flags)
self.disabled = frozenset(disabled_flags)
self.conditional = None
for v in conditional.itervalues():
if v:
for k, v in conditional.iteritems():
conditional[k] = frozenset(v)
self.conditional = conditional
break
def _validate_flag(self, token, flag):
if self._valid_use_re.match(flag) is None:
raise InvalidAtom(_("Invalid use dep: '%s'") % (token,))
return flag
def __nonzero__(self):
return bool(self.tokens)
def __str__(self):
if not self.tokens:
return ""
return "[%s]" % (",".join(self.tokens),)
def __repr__(self):
return "portage.dep._use_dep(%s)" % repr(self.tokens)
def evaluate_conditionals(self, use):
"""
Create a new instance with conditionals evaluated.
Conditional evaluation behavior:
parent state conditional result
x x? x
-x x?
x !x?
-x !x? -x
x x= x
-x x= -x
x !x= -x
-x !x= x
Conditional syntax examples:
Compact Form Equivalent Expanded Form
foo[bar?] bar? ( foo[bar] ) !bar? ( foo )
foo[!bar?] bar? ( foo ) !bar? ( foo[-bar] )
foo[bar=] bar? ( foo[bar] ) !bar? ( foo[-bar] )
foo[!bar=] bar? ( foo[-bar] ) !bar? ( foo[bar] )
"""
tokens = []
conditional = self.conditional
tokens.extend(self.enabled)
tokens.extend("-" + x for x in self.disabled)
tokens.extend(x for x in conditional.enabled if x in use)
tokens.extend("-" + x for x in conditional.disabled if x not in use)
tokens.extend(x for x in conditional.equal if x in use)
tokens.extend("-" + x for x in conditional.equal if x not in use)
tokens.extend("-" + x for x in conditional.not_equal if x in use)
tokens.extend(x for x in conditional.not_equal if x not in use)
return _use_dep(tokens)
def _eval_qa_conditionals(self, use_mask, use_force):
"""
For repoman, evaluate all possible combinations within the constraints
of the given use.force and use.mask settings. The result may seem
ambiguous in the sense that the same flag can be in both the enabled
and disabled sets, but this is useful within the context of how its
intended to be used by repoman. It is assumed that the caller has
already ensured that there is no intersection between the given
use_mask and use_force sets when necessary.
"""
tokens = []
conditional = self.conditional
tokens.extend(self.enabled)
tokens.extend("-" + x for x in self.disabled)
tokens.extend(x for x in conditional.enabled if x not in use_mask)
tokens.extend("-" + x for x in conditional.disabled if x not in use_force)
tokens.extend(x for x in conditional.equal if x not in use_mask)
tokens.extend("-" + x for x in conditional.equal if x not in use_force)
tokens.extend("-" + x for x in conditional.not_equal if x not in use_mask)
tokens.extend(x for x in conditional.not_equal if x not in use_force)
return _use_dep(tokens)
class _AtomCache(type):
"""
Cache Atom instances from constructor calls and reuse
identical instances when available.
"""
def __call__(cls, s):
if isinstance(s, Atom):
return s
instance = cls._atoms.get(s)
if instance is None:
instance = super(_AtomCache, cls).__call__(s)
cls._atoms[s] = instance
return instance
class Atom(object):
"""
For compatibility with existing atom string manipulation code, this
class emulates most of the str methods that are useful with atoms.
"""
__metaclass__ = _AtomCache
_atoms = weakref.WeakValueDictionary()
__slots__ = ("__weakref__", "blocker", "cp", "cpv", "operator",
"slot", "use", "without_use", "_str",)
class _blocker(object):
__slots__ = ("overlap",)
class _overlap(object):
__slots__ = ("forbid",)
def __init__(self, forbid=False):
self.forbid = forbid
def __init__(self, forbid_overlap=False):
self.overlap = self._overlap(forbid=forbid_overlap)
def __init__(self, s):
if not isvalidatom(s, allow_blockers=True):
raise InvalidAtom(s)
obj_setattr = object.__setattr__
obj_setattr(self, '_str', s)
blocker = "!" == s[:1]
if blocker:
blocker = self._blocker(forbid_overlap=("!" == s[1:2]))
if blocker.overlap.forbid:
s = s[2:]
else:
s = s[1:]
else:
blocker = False
obj_setattr(self, "blocker", blocker)
obj_setattr(self, "cp", dep_getkey(s))
obj_setattr(self, "cpv", dep_getcpv(s))
obj_setattr(self, "slot", dep_getslot(s))
obj_setattr(self, "operator", get_operator(s))
use = dep_getusedeps(s)
if use:
use = _use_dep(use)
without_use = remove_slot(self)
if self.slot is not None:
without_use += ":" + self.slot
without_use = Atom(without_use)
else:
use = None
without_use = self
obj_setattr(self, "use", use)
obj_setattr(self, "without_use", without_use)
def __setattr__(self, name, value):
raise AttributeError("Atom instances are immutable",
self.__class__, name, value)
def intersects(self, other):
"""
Atoms with different cpv, operator or use attributes cause this method
to return False even though there may actually be some intersection.
TODO: Detect more forms of intersection.
@param other: The package atom to match
@type other: Atom
@rtype: Boolean
@return: True if this atom and the other atom intersect,
False otherwise.
"""
if not isinstance(other, Atom):
raise TypeError("expected %s, got %s" % \
(Atom, type(other)))
if self == other:
return True
if self.cp != other.cp or \
self.use != other.use or \
self.operator != other.operator or \
self.cpv != other.cpv:
return False
if self.slot is None or \
other.slot is None or \
self.slot == other.slot:
return True
return False
# Implement some common str methods.
def __eq__(self, other):
return self._str == other
def __getitem__(self, key):
return self._str[key]
def __hash__(self):
return hash(self._str)
def __len__(self):
return len(self._str)
def __lt__(self, other):
return self._str < other
def __ne__(self, other):
return self._str != other
def __repr__(self):
return repr(self._str)
def __str__(self):
return self._str
def endswith(self, *pargs, **kargs):
return self._str.endswith(*pargs, **kargs)
def find(self, *pargs, **kargs):
return self._str.find(*pargs, **kargs)
def index(self, *pargs, **kargs):
return self._str.index(*pargs, **kargs)
def lstrip(self, *pargs, **kargs):
return self._str.lstrip(*pargs, **kargs)
def replace(self, *pargs, **kargs):
return self._str.replace(*pargs, **kargs)
def startswith(self, *pargs, **kargs):
return self._str.startswith(*pargs, **kargs)
def split(self, *pargs, **kargs):
return self._str.split(*pargs, **kargs)
def strip(self, *pargs, **kargs):
return self._str.strip(*pargs, **kargs)
def rindex(self, *pargs, **kargs):
return self._str.rindex(*pargs, **kargs)
def rfind(self, *pargs, **kargs):
return self._str.rfind(*pargs, **kargs)
def rstrip(self, *pargs, **kargs):
return self._str.rstrip(*pargs, **kargs)
def __copy__(self):
"""Immutable, so returns self."""
return self
def __deepcopy__(self, memo=None):
"""Immutable, so returns self."""
memo[id(self)] = self
return self
def get_operator(mydep):
"""
Return the operator used in a depstring.
Example usage:
>>> from portage.dep import *
>>> get_operator(">=test-1.0")
'>='
@param mydep: The dep string to check
@type mydep: String
@rtype: String
@return: The operator. One of:
'~', '=', '>', '<', '=*', '>=', or '<='
"""
operator = getattr(mydep, "operator", False)
if operator is not False:
return operator
if mydep:
mydep = remove_slot(mydep)
if not mydep:
return None
if mydep[0] == "~":
operator = "~"
elif mydep[0] == "=":
if mydep[-1] == "*":
operator = "=*"
else:
operator = "="
elif mydep[0] in "><":
if len(mydep) > 1 and mydep[1] == "=":
operator = mydep[0:2]
else:
operator = mydep[0]
else:
operator = None
return operator
_dep_getcpv_cache = {}
def dep_getcpv(mydep):
"""
Return the category-package-version with any operators/slot specifications stripped off
Example usage:
>>> dep_getcpv('>=media-libs/test-3.0')
'media-libs/test-3.0'
@param mydep: The depstring
@type mydep: String
@rtype: String
@return: The depstring with the operator removed
"""
cpv = getattr(mydep, "cpv", None)
if cpv is not None:
return cpv
global _dep_getcpv_cache
retval = _dep_getcpv_cache.get(mydep, None)
if retval is not None:
return retval
mydep_orig = mydep
if mydep:
mydep = remove_slot(mydep)
if mydep and mydep[0] == "*":
mydep = mydep[1:]
if mydep and mydep[-1] == "*":
mydep = mydep[:-1]
if mydep and mydep[0] == "!":
if mydep[1:2] == "!":
mydep = mydep[2:]
else:
mydep = mydep[1:]
if mydep[:2] in [">=", "<="]:
mydep = mydep[2:]
elif mydep[:1] in "=<>~":
mydep = mydep[1:]
_dep_getcpv_cache[mydep_orig] = mydep
return mydep
def dep_getslot(mydep):
"""
Retrieve the slot on a depend.
Example usage:
>>> dep_getslot('app-misc/test:3')
'3'
@param mydep: The depstring to retrieve the slot of
@type mydep: String
@rtype: String
@return: The slot
"""
slot = getattr(mydep, "slot", False)
if slot is not False:
return slot
colon = mydep.find(":")
if colon != -1:
bracket = mydep.find("[", colon)
if bracket == -1:
return mydep[colon+1:]
else:
return mydep[colon+1:bracket]
return None
def remove_slot(mydep):
"""
Removes dep components from the right side of an atom:
* slot
* use
* repo
"""
colon = mydep.find(":")
if colon != -1:
mydep = mydep[:colon]
else:
bracket = mydep.find("[")
if bracket != -1:
mydep = mydep[:bracket]
return mydep
def dep_getusedeps( depend ):
"""
Pull a listing of USE Dependencies out of a dep atom.
Example usage:
>>> dep_getusedeps('app-misc/test:3[foo,-bar]')
('foo', '-bar')
@param depend: The depstring to process
@type depend: String
@rtype: List
@return: List of use flags ( or [] if no flags exist )
"""
use = getattr(depend, "use", None)
if use is not None and hasattr(use, "tokens"):
return use.tokens
use_list = []
open_bracket = depend.find('[')
# -1 = failure (think c++ string::npos)
comma_separated = False
bracket_count = 0
while( open_bracket != -1 ):
bracket_count += 1
if bracket_count > 1:
raise InvalidAtom(_("USE Dependency with more "
"than one set of brackets: %s") % (depend,))
close_bracket = depend.find(']', open_bracket )
if close_bracket == -1:
raise InvalidAtom(_("USE Dependency with no closing bracket: %s") % depend )
use = depend[open_bracket + 1: close_bracket]
# foo[1:1] may return '' instead of None, we don't want '' in the result
if not use:
raise InvalidAtom(_("USE Dependency with "
"no use flag ([]): %s") % depend )
if not comma_separated:
comma_separated = "," in use
if comma_separated and bracket_count > 1:
raise InvalidAtom(_("USE Dependency contains a mixture of "
"comma and bracket separators: %s") % depend )
if comma_separated:
for x in use.split(","):
if x:
use_list.append(x)
else:
raise InvalidAtom(_("USE Dependency with no use "
"flag next to comma: %s") % depend )
else:
use_list.append(use)
# Find next use flag
open_bracket = depend.find( '[', open_bracket+1 )
return tuple(use_list)
# \w is [a-zA-Z0-9_]
# 2.1.1 A category name may contain any of the characters [A-Za-z0-9+_.-].
# It must not begin with a hyphen or a dot.
_cat = r'[\w+][\w+.-]*'
# 2.1.2 A package name may contain any of the characters [A-Za-z0-9+_-].
# It must not begin with a hyphen,
# and must not end in a hyphen followed by one or more digits.
_pkg = \
r'''([\w+](
-? # All other 2-char are handled by next
|[\w+]* # No hyphens - no problems
|[\w+-]+( # String with a hyphen...
[A-Za-z+_-] # ... must end in nondigit
|[A-Za-z+_][\w+]+ # ... or in nondigit and then nonhyphens
)
))'''
# 2.1.3 A slot name may contain any of the characters [A-Za-z0-9+_.-].
# It must not begin with a hyphen or a dot.
_slot = r'(:[\w+][\w+.-]*)?'
_use = r'(\[.*\])?'
_op = r'([=~]|[><]=?)'
_cp = _cat + '/' + _pkg
_cpv = _cp + '-' + _version
_cpv_re = re.compile('^' + _cpv + '$', re.VERBOSE)
_atom_re = re.compile(r'^(' +
'(' + _op + _cpv + _slot + _use + ')|' +
'(=' + _cpv + r'\*' + _slot + _use + ')|' +
'(' + _cp + _slot + _use + ')' +
')$', re.VERBOSE)
def isvalidatom(atom, allow_blockers=False):
"""
Check to see if a depend atom is valid
Example usage:
>>> isvalidatom('media-libs/test-3.0')
False
>>> isvalidatom('>=media-libs/test-3.0')
True
@param atom: The depend atom to check against
@type atom: String or Atom
@rtype: Boolean
@return: One of the following:
1) False if the atom is invalid
2) True if the atom is valid
"""
existing_atom = Atom._atoms.get(atom)
if existing_atom is not None:
atom = existing_atom
if isinstance(atom, Atom):
return allow_blockers or not atom.blocker
if len(atom) < 2:
return False
if allow_blockers and atom[0] == '!':
if atom[1] == '!':
atom = atom[2:]
else:
atom = atom[1:]
if _atom_re.match(atom) is None:
return False
try:
use = dep_getusedeps(atom)
if use:
use = _use_dep(use)
return True
except InvalidAtom:
return False
def isjustname(mypkg):
"""
Checks to see if the atom is only the package name (no version parts).
Raises InvalidAtom if the input is invalid.
Example usage:
>>> isjustname('=media-libs/test-3.0')
False
>>> isjustname('media-libs/test')
True
@param mypkg: The package atom to check
@param mypkg: String or Atom
@rtype: Integer
@return: One of the following:
1) False if the package string is not just the package name
2) True if it is
"""
try:
return mypkg == Atom(mypkg).cp
except InvalidAtom:
pass
myparts = mypkg.split('-')
for x in myparts:
if ververify(x):
return False
return True
iscache = {}
def isspecific(mypkg):
"""
Checks to see if a package is in category/package-version or package-version format,
possibly returning a cached result.
Example usage:
>>> isspecific('media-libs/test')
False
>>> isspecific('media-libs/test-3.0')
True
@param mypkg: The package depstring to check against
@type mypkg: String
@rtype: Boolean
@return: One of the following:
1) False if the package string is not specific
2) True if it is
"""
try:
return iscache[mypkg]
except KeyError:
pass
retval = _cpv_re.match(mypkg) is not None
iscache[mypkg] = retval
return retval
def dep_getkey(mydep):
"""
Return the category/package-name of a depstring.
Example usage:
>>> dep_getkey('media-libs/test-3.0')
'media-libs/test'
@param mydep: The depstring to retrieve the category/package-name of
@type mydep: String
@rtype: String
@return: The package category/package-version
"""
cp = getattr(mydep, "cp", None)
if cp is not None:
return cp
mydep = dep_getcpv(mydep)
if mydep and isspecific(mydep):
mysplit = catpkgsplit(mydep)
if not mysplit:
return mydep
return mysplit[0] + "/" + mysplit[1]
else:
return mydep
def match_to_list(mypkg, mylist):
"""
Searches list for entries that matches the package.
@param mypkg: The package atom to match
@type mypkg: String
@param mylist: The list of package atoms to compare against
@param mylist: List
@rtype: List
@return: A unique list of package atoms that match the given package atom
"""
matches = []
for x in mylist:
if match_from_list(x, [mypkg]):
if x not in matches:
matches.append(x)
return matches
def best_match_to_list(mypkg, mylist):
"""
Returns the most specific entry that matches the package given.
@param mypkg: The package atom to check
@type mypkg: String
@param mylist: The list of package atoms to check against
@type mylist: List
@rtype: String
@return: The package atom which best matches given the following ordering:
- =cpv 6
- ~cpv 5
- =cpv* 4
- cp:slot 3
- >cpv 2
- <cpv 2
- >=cpv 2
- <=cpv 2
- cp 1
"""
operator_values = {'=':6, '~':5, '=*':4,
'>':2, '<':2, '>=':2, '<=':2, None:1}
maxvalue = 0
bestm = None
for x in match_to_list(mypkg, mylist):
if dep_getslot(x) is not None:
if maxvalue < 3:
maxvalue = 3
bestm = x
op_val = operator_values[get_operator(x)]
if op_val > maxvalue:
maxvalue = op_val
bestm = x
return bestm
def match_from_list(mydep, candidate_list):
"""
Searches list for entries that matches the package.
@param mydep: The package atom to match
@type mydep: String
@param candidate_list: The list of package atoms to compare against
@param candidate_list: List
@rtype: List
@return: A list of package atoms that match the given package atom
"""
if not candidate_list:
return []
from portage.util import writemsg
if "!" == mydep[:1]:
mydep = mydep[1:]
if not isinstance(mydep, Atom):
mydep = Atom(mydep)
mycpv = dep_getcpv(mydep)
mycpv_cps = catpkgsplit(mycpv) # Can be None if not specific
slot = dep_getslot(mydep)
if not mycpv_cps:
cat, pkg = catsplit(mycpv)
ver = None
rev = None
else:
cat, pkg, ver, rev = mycpv_cps
if mydep == mycpv:
raise KeyError(_("Specific key requires an operator"
" (%s) (try adding an '=')") % (mydep))
if ver and rev:
operator = get_operator(mydep)
if not operator:
writemsg(_("!!! Invalid atom: %s\n") % mydep, noiselevel=-1)
return []
else:
operator = None
mylist = []
if operator is None:
for x in candidate_list:
cp = getattr(x, "cp", None)
if cp is None:
cp = dep_getkey(x)
if cp != mycpv:
continue
mylist.append(x)
elif operator == "=": # Exact match
for x in candidate_list:
xcpv = getattr(x, "cpv", None)
if xcpv is None:
xcpv = dep_getcpv(x)
if not cpvequal(xcpv, mycpv):
continue
mylist.append(x)
elif operator == "=*": # glob match
# XXX: Nasty special casing for leading zeros
# Required as =* is a literal prefix match, so can't
# use vercmp
mysplit = catpkgsplit(mycpv)
myver = mysplit[2].lstrip("0")
if not myver or not myver[0].isdigit():
myver = "0"+myver
mycpv = mysplit[0]+"/"+mysplit[1]+"-"+myver
for x in candidate_list:
xs = getattr(x, "cpv_split", None)
if xs is None:
xs = catpkgsplit(remove_slot(x))
myver = xs[2].lstrip("0")
if not myver or not myver[0].isdigit():
myver = "0"+myver
xcpv = xs[0]+"/"+xs[1]+"-"+myver
if xcpv.startswith(mycpv):
mylist.append(x)
elif operator == "~": # version, any revision, match
for x in candidate_list:
xs = getattr(x, "cpv_split", None)
if xs is None:
xs = catpkgsplit(remove_slot(x))
if xs is None:
raise InvalidData(x)
if not cpvequal(xs[0]+"/"+xs[1]+"-"+xs[2], mycpv_cps[0]+"/"+mycpv_cps[1]+"-"+mycpv_cps[2]):
continue
if xs[2] != ver:
continue
mylist.append(x)
elif operator in [">", ">=", "<", "<="]:
mysplit = ["%s/%s" % (cat, pkg), ver, rev]
for x in candidate_list:
xs = getattr(x, "cpv_split", None)
if xs is None:
xs = catpkgsplit(remove_slot(x))
xcat, xpkg, xver, xrev = xs
xs = ["%s/%s" % (xcat, xpkg), xver, xrev]
try:
result = pkgcmp(xs, mysplit)
except ValueError: # pkgcmp may return ValueError during int() conversion
writemsg(_("\nInvalid package name: %s\n") % x, noiselevel=-1)
raise
if result is None:
continue
elif operator == ">":
if result > 0:
mylist.append(x)
elif operator == ">=":
if result >= 0:
mylist.append(x)
elif operator == "<":
if result < 0:
mylist.append(x)
elif operator == "<=":
if result <= 0:
mylist.append(x)
else:
raise KeyError(_("Unknown operator: %s") % mydep)
else:
raise KeyError(_("Unknown operator: %s") % mydep)
if slot is not None:
candidate_list = mylist
mylist = []
for x in candidate_list:
xslot = getattr(x, "slot", False)
if xslot is False:
xslot = dep_getslot(x)
if xslot is not None and xslot != slot:
continue
mylist.append(x)
if mydep.use:
candidate_list = mylist
mylist = []
for x in candidate_list:
use = getattr(x, "use", None)
if use is not None:
regex = x.iuse.regex
missing_iuse = False
for y in mydep.use.required:
if regex.match(y) is None:
missing_iuse = True
break
if missing_iuse:
continue
if mydep.use.enabled.difference(use.enabled):
continue
if mydep.use.disabled.intersection(use.enabled):
continue
mylist.append(x)
return mylist
|