Coverage for pandalone.mappings: 94%

# Coverage for pandalone.mappings : 94%

## 325 statements 307 run 18 missing 2 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

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 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 | #! python #-*- coding: utf-8 -*- # # Copyright 2013-2015 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl """ Hierarchical string-like objects useful for indexing, that can be rename/relocated at a later stage. .. autosummary:: Pstep pmods_from_tuples Pmod *Example*:: >>> from pandalone.mappings import pmods_from_tuples >>> pmods = pmods_from_tuples([ ... ('', 'deeper/ROOT'), ... ('/abc', 'ABC'), ... ('/abc/foo', 'BAR'), ... ]) >>> p = pmods.step() >>> p.abc.foo `BAR` >>> p._paths() ['deeper/ROOT/ABC/BAR'] - TODO: Implements "anywhere" pmods(`//`). """ from __future__ import division, unicode_literals from collections import OrderedDict from copy import copy import logging import re from past.builtins import basestring import functools as ft from pandalone import utils from pandalone.pandata import ( iter_jsonpointer_parts_relaxed, JSchema, unescape_jsonpointer_part, escape_jsonpointer_part) __commit__ = "" log = logging.getLogger(__name__) class Pmod(object): r""" A path-step mapping forming the pmods-hierarchy. - The :term:`pmods` denotes the hierarchy of all :term:`mappings`, that either *rename* or *relocate* path-steps. - A single :term:`mapping` transforms an "origin" path to a "destination" one (also called as "from" and "to" paths). - A mapping always transforms the *final* path-step, like that:: FROM_PATH TO_PATH RESULT_PATH --------- ------- ----------- /rename/path foo --> /rename/foo ## renaming /relocate/path foo/bar --> /relocate/foo/bar ## relocation '' a/b/c --> /a/b/c ## Relocate all paths. / a/b/c --> /a/b/c ## Relocates 1st "empty-str" step. - The :term:`pmod` is the mapping of that single path-step. - It is possible to match fully on path-steps using regular-expressions, and then to use any captured-groups from the *final* step into the mapped value:: (/all(.*)/path, foo) + all_1/path --> /all_1/foo + all_XYZ --> /all_XYZ ## no change (/all(.*)/path, foo\1) + all_1/path --> /all_1/foo_1 If more than one regex match, they are merged in the order declared (the latest one overrides a previous one). - Any exact child-name matches are applied and merged after regexs. - Use :func:`pmods_from_tuples()` to construct the pmods-hierarchy. - The pmods are used internally by class:`Pstep` to correspond the component-paths of their input & output onto the actual value-tree paths. :ivar str _alias: (optional) the mapped-name of the pstep for this pmod :ivar dict _steps: {original_name --> pmod} :ivar OrderedDict _regxs: {regex_on_originals --> pmod} Example: .. Note:: Do not manually construct instances from this class! To construct a hierarchy use the :func:`pmods_from_tuples()`. You can either use it for massively map paths, either for *renaming* them:: >>> pmods = pmods_from_tuples([ ... ('/a', 'A'), ... ('/~b.*', r'BB\g<0>'), ## Previous match. ... ('/~b.*/~c.(.*)', r'W\1ER'), ## Capturing-group(1) ... ]) >>> pmods.map_paths(['/a', '/a/foo']) ## 1st rule ['/A', '/A/foo'] >>> pmods.map_path('/big/stuff') ## 2nd rule '/BBbig/stuff' >>> pmods.map_path('/born/child') ## 2nd & 3rd rule '/BBborn/WildER' or to *relocate* them:: >>> pmods = pmods_from_tuples([ ... ('/a', 'A/AA'), ... ('/~b.*/~c(.*)', r'../C/\1'), ... ('/~b.*/~.*/~r.*', r'/\g<0>'), ... ]) >>> pmods.map_paths(['/a/foo', '/big/child', '/begin/from/root']) ['/A/AA/foo', '/big/C/hild', '/root'] Here is how you relocate "root" (notice that the `''` path is the root):: >>> pmods = pmods_from_tuples([('', '/NEW/ROOT')]) >>> pmods.map_paths(['/a/foo', '']) ['/NEW/ROOT/a/foo', '/NEW/ROOT'] """ __slots__ = ['_alias', '_steps', '_regxs'] def __init__(self, _alias=None, _steps={}, _regxs={}): """ Args passed only for testing, remember `_regxs` to be (k,v) tuple-list! .. Note:: Volatile arg-defaults (empty dicts) are knowingly used , to preserve memory; should never append in them! """ self._alias = _alias self._steps = _steps if _regxs: self._regxs = OrderedDict( (re.compile(k), v) for k, v in _regxs) else: self._regxs = _regxs def step(self, pname='', alias=None): """ Create a new :class:`Pstep` having as mappings this pmod. If no `pname` specified, creates a *root* pstep. Delegates to :meth:`Pstep.__new__()`. """ return Pstep(pname, _proto_or_pmod=self, alias=alias) def _append_into_steps(self, key): """ Inserts a child-mappings into `_steps` dict. :param str key: the step-name to add """ cpmod = None d = self._steps if not d: self._steps = d = {} # Do not modify init-defaults. else: cpmod = d.get(key) if not cpmod: d[key] = cpmod = Pmod() return cpmod def _append_into_regxs(self, key): """ Inserts a child-mappings into `_steps` dict. :param str key: the regex-pattern to add """ key = re.compile(key) cpmod = None d = self._regxs if not d: self._regxs = d = OrderedDict() # Do not modify init-defaults. else: cpmod = d.get(key) if cpmod: # Remove it, to append it at then end. del d[key] if not cpmod: cpmod = Pmod() d[key] = cpmod return cpmod def _override_steps(self, other): """ Override this pmod's '_steps' dict with other's, recursively. Same as :meth:`_override_regxs()` but without caring for order. """ opmods = other._steps if opmods: spmods = self._steps if spmods: # Like ``spmods.copy().update()`` but # recursive `_merge()` on common items. # spmods = spmods.copy() for name, opmod in opmods.items(): spmod = spmods.get(name) if spmod: opmod = spmod._merge(opmod) spmods[name] = opmod # Share other-pmod if not mine. opmods = spmods # Share other dict if self hadn't its own. self._steps = opmods def _override_regxs(self, other): """ Override this pmod's `_regxs` dict with other's, recursively. - It may "share" (crosslink) the dict and/or its child-pmods between the two pmod args (`self` and `other`). - No dict is modified (apart from self, which must have been cloned previously by :meth:`Pmod._merge()`), to avoid side-effects in case they were "shared". - It preserves dict-ordering so that `other` order takes precedence (its elements are the last ones). :param Pmod self: contains the dict that would be overridden :param Pmod other: contains the dict with the overrides """ opmods = other._regxs if opmods: spmods = self._regxs if spmods: # Like ``spmods.copy().update()`` but # with recursive `_merge()` on common items, # and preserve order. # opairs = [] for name, opmod in opmods.items(): spmod = spmods.get(name) if spmod: mpmod = spmod._merge(opmod) else: mpmod = opmod # Share other-pmod. opairs.append((name, mpmod)) okeys = opmods.keys() spairs = [(name, spmod) # Share self-pmod. for name, spmod in spmods.items() if name not in okeys] opmods = type(spmods)(spairs + opairs) # Share other dict if self hadn't its own. self._regxs = opmods def _merge(self, other): """ Clone and override all its props with props from other-pmod, recursively. Although it does not modify this, the `other` or their children pmods, it may "share" (crosslink) them, so pmods MUST NOT be modified later. :param Pmod other: contains the dicts with the overrides :return: the cloned merged pmod :rtype: Pmod Examples: Look how `_steps` are merged:: >>> pm1 = Pmod(_alias='pm1', _steps={ ... 'a':Pmod(_alias='A'), 'c':Pmod(_alias='C')}) >>> pm2 = Pmod(_alias='pm2', _steps={ ... 'b':Pmod(_alias='B'), 'a':Pmod(_alias='AA')}) >>> pm = pm1._merge(pm2) >>> sorted(pm._steps.keys()) ['a', 'b', 'c'] And here it is `_regxs` merging, which preserves order:: >>> pm1 = Pmod(_alias='pm1', ... _regxs=[('d', Pmod(_alias='D')), ... ('a', Pmod(_alias='A')), ... ('c', Pmod(_alias='C'))]) >>> pm2 = Pmod(_alias='pm2', ... _regxs=[('b', Pmod(_alias='BB')), ... ('a', Pmod(_alias='AA'))]) >>> pm1._merge(pm2) pmod('pm2', OrderedDict([(re.compile('d'), pmod('D')), (re.compile('c'), pmod('C')), (re.compile('b'), pmod('BB')), (re.compile('a'), pmod('AA'))])) >>> pm2._merge(pm1) pmod('pm1', OrderedDict([(re.compile('b'), pmod('BB')), (re.compile('d'), pmod('D')), (re.compile('a'), pmod('A')), (re.compile('c'), pmod('C'))])) """ self = copy(self) if other._alias is not None: self._alias = other._alias self._override_steps(other) self._override_regxs(other) return self def _match_regxs(self, cstep): """Return (pmod, regex.match) for those child-pmods matching `cstep`.""" return [(rpmod, match) for rpmod, match in ((rpmod, utils.fullmatch(regex, cstep)) for regex, rpmod in self._regxs.items()) if match] def descend(self, cstep): r""" Return child-pmod with merged any exact child with all matched regexps, along with its alias regex-expaned. :param str cstep: the child path-step cstep of the pmod to return :return: the merged-child pmod, along with the alias; both might be None, if nothing matched, or no alias. :rtype: tuple(Pmod, str) Example:: >>> pm = Pmod( ... _steps={'a': Pmod(_alias='A')}, ... _regxs=[('a\w*', Pmod(_alias='AWord')), ... ('a(\d*)', Pmod(_alias=r'A_\1')), ... ]) >>> pm.descend('a') (pmod('A'), 'A') >>> pm.descend('abc') (pmod('AWord'), 'AWord') >>> pm.descend('a12') (pmod('A_\\1'), 'A_12') >>> pm.descend('BAD') (None, None) Notice how children of regexps are merged together:: >>> pm = Pmod( ... _steps={'a': ... Pmod(_alias='A', _steps={1: 11})}, ... _regxs=[ ... (r'a\w*', Pmod(_alias='AWord', ... _steps={2: Pmod(_alias=22)})), ... (r'a\d*', Pmod(_alias='ADigit', ... _steps={3: Pmod(_alias=33)})), ... ]) >>> sorted(pm.descend('a')[0]._steps) ## All children and regexps match. [1, 2, 3] >>> pm.descend('aa')[0]._steps ## Only 'a\w*' matches. {2: pmod(22)} >>> sorted(pm.descend('a1')[0]._steps ) ## Both regexps matches. [2, 3] So it is possible to say:: >>> pm.descend('a1')[0].alias(2) 22 >>> pm.descend('a1')[0].alias(3) 33 >>> pm.descend('a1')[0].descend('BAD') (None, None) >>> pm.descend('a$') (None, None) but it is better to use :meth:`map_path()` for this. """ alias = None cpmod = self._steps.get(cstep) pmods = self._match_regxs(cstep) if cpmod and cpmod._alias is not None: alias = cpmod._alias else: for rpmod, match in reversed(pmods): if rpmod._alias is not None: alias = match.expand(rpmod._alias) break pmods = [pmod for pmod, _ in pmods] if cpmod: pmods.append(cpmod) if pmods: return (ft.reduce(Pmod._merge, pmods), alias) return (None, None) def alias(self, cstep): """ Like :meth:`descend()` but without merging child-pmods. :return: the expanded alias from child/regexs or None """ cpmod = self._steps.get(cstep) if cpmod and cpmod._alias is not None: return cpmod._alias pmods = self._match_regxs(cstep) for rpmod, match in reversed(pmods): if rpmod._alias is not None: return match.expand(rpmod._alias) def map_path(self, path): r""" Maps a '/rooted/path' using all aliases while descending its child pmods. It uses any aliases on all child pmods if found. :param str path: a rooted path to transform :return: the rooted mapped path or '/' if path was '/' :rtype: str or None Examples:: >>> pmods = pmods_from_tuples([ ... ('/a', 'A/AA'), ... ('/~a(\\w*)', r'BB\1'), ... ('/~a\\w*/~d.*', r'D \g<0>'), ... ('/~a(\\d+)', r'C/\1'), ... ('/~a(\\d+)/~(c.*)', r'CC-/\1'), # The 1st group is ignored! ... ('/~a\\d+/~e.*', r'/newroot/\g<0>'), # Rooted mapping. ... ]) >>> pmods.map_path('/a') '/A/AA' >>> pmods.map_path('/a_hi') '/BB_hi' >>> pmods.map_path('/a12') '/C/12' >>> pmods.map_path('/a12/etc') '/newroot/etc' Notice how children from *all* matching prior-steps are merged:: >>> pmods.map_path('/a12/dow') '/C/12/D dow' >>> pmods.map_path('/a12/cow') '/C/12/CC-/cow' To map *root* use '' which matches before the 1st slash('/'):: >>> pmods = pmods_from_tuples([('', 'New/Root'),]) ## Relative >>> pmods pmod({'': pmod('New/Root')}) >>> pmods.map_path('/for/plant') 'New/Root/for/plant' >>> pmods_from_tuples([('', '/New/Root'),]).map_path('/for/plant') '/New/Root/for/plant' .. Note:: Using slash('/') for "from" path will NOT map *root*:: >>> pmods = pmods_from_tuples([('/', 'New/Root'),]) >>> pmods pmod({'': pmod({'': pmod('New/Root')})}) >>> pmods.map_path('/for/plant') '/for/plant' >>> pmods.map_path('//for/plant') '/New/Root/for/plant' '/root' but '' always remains unchanged (whole document):: >>> pmods.map_path('') '' """ is_folder = len(path) > 1 and path.endswith('/') if is_folder: path = path[:-1] steps = tuple(iter_jsonpointer_parts_relaxed(path)) if self._alias is None: nsteps = () else: nsteps = tuple(iter_jsonpointer_parts_relaxed(self._alias)) if steps: pmod = self # Separate last-step from loop below, since # merged child-pmods in `descend` are not needed. # for step in steps[:-1]: if pmod: pmod, alias = pmod.descend(step) if alias is not None: if alias.startswith('.'): nsteps += (step, ) step = alias # XXX: Monkey business here. if len(step) > 1 and step.endswith('/'): step = step[:-1] nsteps += tuple(iter_jsonpointer_parts_relaxed(step)) final_step = steps[-1] if pmod: alias = pmod.alias(final_step) if alias is not None: if alias.startswith('.'): nsteps += (final_step, ) final_step = alias # XXX: Monkey business here. is_folder = len(final_step) > 1 and final_step.endswith('/') if is_folder: final_step = final_step[:-1] nsteps += tuple(iter_jsonpointer_parts_relaxed(final_step)) npath = _join_paths(*nsteps) if is_folder: path += '%s/' % path return npath def map_paths(self, paths): return [self.map_path(p) for p in paths] def __repr__(self): args = [repr(a) for a in [self._alias, self._steps, self._regxs] if a or a == ''] args = ', '.join(args) return 'pmod({})'.format(args) def __eq__(self, o): try: return (self._alias, self._steps, self._regxs) == (o._alias, o._steps, o._regxs) except: return False def pmods_from_tuples(pmods_tuples): """ Turns a list of 2-tuples into a *pmods* hierarchy. - Each tuple defines the renaming-or-relocation of the *final* part of some component path onto another one into value-trees, such as:: (/rename/path, foo) --> rename/foo (relocate/path, foo/bar) --> relocate/foo/bar - The "from" path may be: - relative, - absolute(starting with `/`), or - "anywhere"(starting with `//`). - In case a "step" in the "from" path starts with tilda(`~`), it is assumed to be a regular-expression, and it is removed from it. The "to" path can make use of any "from" capture-groups:: ('/~all(.*)/path', 'foo') ('~some[\d+]/path', 'foo\1') ('//~all(.*)/path', 'foo') :param list(tuple(str, str) pmods_tuples: :return: a root pmod :rtype: Pmod Example:: >>> pmods_from_tuples([ ... ('/a', 'A1/A2'), ... ('/a/b', 'B'), ... ]) pmod({'': pmod({'a': pmod('A1/A2', {'b': pmod('B')})})}) >>> pmods_from_tuples([ ... ('/~a*', 'A1/A2'), ... ('/a/~b[123]', 'B'), ... ]) pmod({'': pmod({'a': pmod(OrderedDict([(re.compile('b[123]'), pmod('B'))]))}, OrderedDict([(re.compile('a*'), pmod('A1/A2'))]))}) This is how you map *root*:: >>> pmods = pmods_from_tuples([ ... ('', 'relative/Root'), ## Make all paths relatives. ... ('/a/b', '/Rooted/B'), ## But map `b` would be "rooted". ... ]) >>> pmods pmod({'': pmod('relative/Root', {'a': pmod({'b': pmod('/Rooted/B')})})}) >>> pmods.map_path('/a/c') 'relative/Root/a/c' >>> pmods.map_path('/a/b') '/Rooted/B' But note that '/' maps the 1st "empty-str" step after root:: >>> pmods_from_tuples([ ... ('/', 'New/Root'), ... ]) pmod({'': pmod({'': pmod('New/Root')})}) TODO: Implement "anywhere" matches. """ root = Pmod() for i, (f, t) in enumerate(pmods_tuples): if (f, t) == ('', '') or f is None or t is None: msg = 'pmod-tuple #%i of %i: Invalid "from-to" tuple (%r, %r).' log.warning(msg, i + 1, len(pmods_tuples), f, t) continue pmod = root for srcstep in iter_jsonpointer_parts_relaxed(f): is_regex = srcstep.startswith('~') if is_regex: pmod = pmod._append_into_regxs(srcstep[1:]) else: pmod = pmod._append_into_steps(srcstep) pmod._alias = t return root def _append_step(steps, step): """ Joins `step` at the right of `steps`, respecting '/', '..', '.', ''. :param tuple steps: where to append into ("absolute" when 1st-element is '') :param str step: what to append (may be: ``'foo', '.', '..', ''``) :rtype: tuple .. Note:: The empty-string('') is the "root" for both `steps` and `step`. An empty-tuple `steps` is considered "relative", equivalent to dot(`.`). Example:: >>> _append_step((), 'a') ('a',) >>> _append_step(('a', 'b'), '..') ('a',) >>> _append_step(('a', 'b'), '.') ('a', 'b') Not that an "absolute" path has the 1st-step empty(`''`), (so the previous paths above were all "relative"):: >>> _append_step(('a', 'b'), '') ('',) >>> _append_step(('',), '') ('',) >>> _append_step((), '') ('',) Dot-dots preserve "relative" and "absolute" paths, respectively, and hence do not coalesce when at the left:: >>> _append_step(('',), '..') ('',) >>> _append_step(('',), '.') ('',) >>> _append_step(('a',), '..') () >>> _append_step((), '..') ('..',) >>> _append_step(('..',), '..') ('..', '..') >>> _append_step((), '.') () Single-dots('.') just dissappear:: >>> _append_step(('.',), '.') () >>> _append_step(('.',), '..') ('..',) """ assert isinstance(steps, tuple), (steps, step) assert not step or isinstance(step, basestring), (steps, step) if step == '': return ('',) _last_pair_choices = { ('.',): (), ('..',): ('..',), ('.', '.'): (), ('.', '..',): ('..',), ('..', '.'): ('..',), ('..', '..'): ('..', '..'), ('', '.'): ('',), ('', '..'): ('',), } try: last_pair = steps[-1:] + (step,) steps = steps[:-1] + _last_pair_choices[last_pair] except KeyError: if step == '.': pass elif step == '..': steps = steps[:-1] else: steps += (step,) return steps def _join_paths(*steps): """ Joins all path-steps in a single string, respecting ``'/', '..', '.', ''``. :param str steps: single json-steps, from left to right :rtype: str .. Note:: If you use :func:`iter_jsonpointer_parts_relaxed()` to generate path-steps, the "root" is signified by the empty(`''`) step; not the slash(`/`)! Hence a lone slash(`/`) gets splitted to an empty step after "root" like that: ``('', '')``, which generates just "root"(`''`). Therefore a "folder" (i.e. `some/folder/`) when splitted equals ``('some', 'folder', '')``, which results again in the "root"(`''`)! Examples:: >>> _join_paths('r', 'a', 'b') 'r/a/b' >>> _join_paths('', 'a', 'b', '..', 'bb', 'cc') '/a/bb/cc' >>> _join_paths('a', 'b', '.', 'c') 'a/b/c' An empty-step "roots" the remaining path-steps:: >>> _join_paths('a', 'b', '', 'r', 'aa', 'bb') '/r/aa/bb' All `steps` have to be already "splitted":: >>> _join_paths('a', 'b', '../bb') 'a/b/../bb' Dot-doting preserves "relative" and "absolute" paths, respectively:: >>> _join_paths('..') '..' >>> _join_paths('a', '..') '.' >>> _join_paths('a', '..', '..', '..') '../..' >>> _join_paths('', 'a', '..', '..') '' Some more special cases:: >>> _join_paths('..', 'a') '../a' >>> _join_paths('', '.', '..', '..') '' >>> _join_paths('.', '..') '..' >>> _join_paths('..', '.', '..') '../..' .. seealso:: _append_step """ nsteps = ft.reduce(_append_step, steps, ()) if not nsteps: return '.' else: return '/'.join(nsteps) class Pstep(str): """ Automagically-constructed *relocatable* paths for accessing data-tree. The "magic" autocreates psteps as they referenced, making writing code that access data-tree paths, natural, while at the same time the "model" of those tree-data gets discovered. Each pstep keeps internally the *name* of a data-tree step, which, when created through recursive referencing, concedes with parent's branch leading to this step. That name can be modified with :class:`Pmod` so the same data-accessing code can refer to differently-named values int the data-tree. :ivar dict _csteps: the child-psteps by their name (default `None`) :ivar dict _pmod: path-modifications used to construct this and relayed to children (default `None`) :ivar int _locked: one of - :const:`Pstep.CAN_RELOCATE` (default), - :const:`Pstep.CAN_RENAME`, - :const:`Pstep.LOCKED` (neither from the above). :ivar set _tags: A set of strings (default `()`) :ivar dict _schema: json-schema data. See :meth:`__new__()` for interal constructor. **Usage:** - Use a :meth:`Pmod.pstep()` to construct a *root* pstep from mappings. Specify a string argument to construct a relative pstep-hierarchy. - Just referencing (non_private) attributes, creates them. - Private attributes and functions (starting with ``_``) exist for specific operations (ie for specifying json-schema, or for collection all paths). - Assignments are only allowed for string-values, or to private attributes:: >>> p = Pstep() >>> p.assignments = 12 Traceback (most recent call last): AssertionError: Cannot assign '12' to '/assignments! >>> p._but_hidden = 'Ok' - Use :meth:`_paths()` to get all defined paths so far. - Construction:: >>> Pstep() `` >>> Pstep('a') `a` Notice that pstesps are surrounded with the back-tick char('`'). - Paths are created implicitely as they are referenced:: >>> m = {'a': 1, 'abc': 2, 'cc': 33} >>> p = Pstep('a') >>> assert m[p] == 1 >>> assert m[p.abc] == 2 >>> assert m[p.a321.cc] == 33 >>> sorted(p._paths()) ['a/a321/cc', 'a/abc'] - Any "path-mappings" or "pmods" maybe specified during construction:: >>> from pandalone.mappings import pmods_from_tuples >>> pmods = pmods_from_tuples([ ... ('', 'deeper/ROOT'), ... ('/abc', 'ABC'), ... ('/abc/foo', 'BAR'), ... ]) >>> p = pmods.step() >>> p.abc.foo `BAR` >>> p._paths() ['deeper/ROOT/ABC/BAR'] - but exceptions are thrown if mapping any step marked as "locked": >>> p.abc.foo._locked ## 3: CAN_RELOCATE 3 >>> p.abc.foo._lock ## Screams, because `foo` is already mapped. Traceback (most recent call last): ValueError: Cannot rename/relocate 'foo'-->'BAR' due to LOCKED! - .. Warning:: Creating an empty(`''`) step in some paths will "root" the path:: >>> p = Pstep() >>> _ = p.a1.b >>> _ = p.A2 >>> p._paths() ['/A2', '/a1/b'] >>> _ = p.a1.a2.c >>> _ = p.a1.a2 = '' >>> p._paths() ['/A2', '/a1/b', '/c'] """ CAN_RELOCATE = 3 CAN_RENAME = 1 LOCKED = 0 @staticmethod def _lockstr(lock): if lock >= Pstep.CAN_RELOCATE: return 'CAN_RELOCATE' if Pstep.LOCKED <= lock < Pstep.CAN_RELOCATE: return 'LOCKED' return 'LOCKED' def __new__(cls, pname='', _proto_or_pmod=None, alias=None): """ Constructs a string with str-content which may comes from the mappings. These are the valid argument combinations:: pname='attr_name', pname='attr_name', _alias='Mass [kg]' pname='attr_name', _proto_or_pmod=Pmod pname='attr_name', _proto_or_pmod=Pstep pname='attr_name', _proto_or_pmod=Pstep, _alias='Mass [kg]' :param str pname: this pstep's name which must coincede with the name of the parent-pstep's attribute holding this pstep. It is stored at `_orig` and if no `alias` and unmapped by pmod, this becomes the `alias`. :param Pmod or Pstep _proto_or_pmod: It can be either: - the mappings for this pstep, - another pstep to clone attributes from (used when replacing an existing child-pstep), or - None. The mappings will apply only if :meth:`Pmod.descend()` match `pname` and will derrive the alias. :param str alias: Will become the super-str object when no mappaings specified (`_proto_or_pmod` is a dict from some prototype pstep) It gets jsonpointer-escaped if it exists (see :func:`pandata.escape_jsonpointer_part()`) """ pmod = None attrs = None if _proto_or_pmod: if isinstance(_proto_or_pmod, Pmod): pmod, m_alias = _proto_or_pmod.descend(pname) if alias is None and m_alias: # TODO: Add Escape-path TCs. alias = unescape_jsonpointer_part(m_alias) else: assert isinstance(_proto_or_pmod, Pstep), ( 'Invalid type(%s) for `_proto_or_pmod`!' % _proto_or_pmod) attrs = _proto_or_pmod.__clone_attrs() if alias is None: alias = pname self = str.__new__(cls, alias) self.__dict__ = attrs or { '_orig': pname, '_pmod': pmod, '_csteps': None, '_locked': Pstep.CAN_RELOCATE, '_tags': () } return self def __clone_attrs(self): """Clone deeply any collection attributes.""" attrs = self.__dict__.copy() ccsteps = attrs.get('_csteps', None) if ccsteps: attrs['_csteps'] = ccsteps.copy() ctags = attrs['_tags'] if ctags: attrs['_tags'] = attrs['_tags'].copy() return attrs def __make_cstep(self, ckey, alias=None, existing_cstep=None): csteps = self._csteps if not csteps: self._csteps = csteps = {} else: if existing_cstep is None: existing_cstep = csteps.get(ckey, None) # Update my mappings for `b` when ``self.b = "foo"``. # if alias is not None: pmod = self._pmod if pmod: pmod._alias = alias else: self._pmod = Pmod(_alias=alias) csteps[ckey] = child = Pstep(ckey, existing_cstep or self._pmod, alias) return child def __getattr__(self, attr): if attr.startswith('_'): msg = "'%s' object has no attribute '%s'" raise AttributeError(msg % (self, attr)) csteps = self._csteps child = csteps and csteps.get(attr, None) return child or self.__make_cstep(attr) def __setattr__(self, attr, value): if attr.startswith('_'): str.__setattr__(self, attr, value) elif isinstance(value, Pstep): self.__make_cstep(attr, existing_cstep=value) elif isinstance(value, basestring): self.__make_cstep(attr, alias=value) else: raise self._ex_invalid_assignment(attr, value) def __dir__(self): d = super(str, self).__dir__() if self._csteps: d = sorted(d + list(self._csteps.keys())) return d def _ex_invalid_assignment(self, cpname, value): msg = "Cannot assign '%s' to '%s/%s!" return AssertionError(msg % (value, self, cpname)) def __repr__(self): return '`%s`' % self @property def _locked(self): """ Gets `_locked` internal flag or scream on set, when step already renamed/relocated Prefer using one of :attr:`_fix` or :attr:`_lock` instead. :param locked: One of :attr:`CAN_RELOCATE`, :attr:`CAN_RENAME`, :attr:`LOCKED`. :raise: ValueError when stricter lock-value on a renamed/relocated pstep """ return vars(self)['_locked'] @_locked.setter def _locked(self, lock_state): if self != self._orig: if lock_state < Pstep.CAN_RENAME or ( lock_state < Pstep.CAN_RELOCATE and '/' in self): msg = "Cannot rename/relocate '%s'-->'%s' due to %s!" raise ValueError( msg % (self._orig, self, Pstep._lockstr(lock_state))) vars(self)['_locked'] = int(lock_state) @property def _fix(self): """Sets :attr:`locked` = `CAN_RENAME`. :return: self :raise: ValueError if step has been relocated pstep """ self._locked = Pstep.CAN_RENAME return self @property def _lock(self): """Set :attr:`locked` = `LOCKED`. :return: self, for chained use :raise: ValueError if step has been renamed/relocated pstep """ self._locked = Pstep.LOCKED return self def _tag(self, tag): """Add a "tag" for this pstep. :return: self, for chained use """ tags = self._tags if tags: tags.add(tag) else: self._tags = set([tag]) return self def _tag_remove(self, tag): """Delete a "tag" from this pstep. :return: self, for chained use """ tags = self._tags if tags: tags.discard(tag) return self def _steps(self, keys=False, tag=None): csteps = self._csteps if not csteps: return [] if keys: return csteps.keys() return csteps.values() def _paths(self, with_orig=False, tag=None): """ Return all children-paths (str-list) constructed so far, in a list. :param bool with_orig: wheter to include also orig-path, for debug. :param str tag: If not 'None', fetches all paths with `tag` in their last step. :rtype: [str] Examples:: >>> p = Pstep() >>> _ = p.a1._tag('inp').b._tag('inp').c >>> _ = p.a2.b2 >>> p._paths() ['/a1/b/c', '/a2/b2'] >>> p._paths(tag='inp') ['/a1', '/a1/b'] For debugging set `with_orig` to `True`:: >>> pmods = pmods_from_tuples([ ... ('', 'ROOT'), ... ('/a', 'A/AA'), ... ]) >>> p = pmods.step() >>> _ = p.a.b >>> p._paths(with_orig=True) ['(-->ROOT)/(a-->A/AA)/b'] """ def append_orig(s): orig = s._orig return '(%s-->%s)' % (orig, s) if s != orig else s paths = [] for path in self._iter_hierarchy(): send = path[-1] if (tag and tag in send._tags) or (not tag and not send._csteps): if with_orig: path = [append_orig(s) for s in path] paths.append(_join_paths(*path)) return sorted(set(paths)) def _derrive_map_tuples(self): """ Recursively extract ``(cmap --> alias)`` pairs from the pstep-hierarchy. :param list pairs: Where to append subtree-paths built. :param tuple prefix_steps: branch currently visiting :rtype: [(str, str)] """ def orig_paths(psteps): return [p._orig for p in psteps] map_pairs = ((_join_paths(*orig_paths(p)), str(p[-1])) for p in self._iter_hierarchy()) return sorted(map_pairs, key=lambda p: p[0]) def _iter_hierarchy(self, prefix_steps=()): """ Breadth-first traversing of pstep-hierarchy. :param tuple prefix_steps: Builds here branch currently visiting. :return: yields the visited pstep along with its path (including it) :rtype: (Pstep, [Pstep]) """ prefix_steps += (self, ) yield prefix_steps csteps = self._csteps if csteps: for v in csteps.values(): for p in v._iter_hierarchy(prefix_steps): yield p @property def _schema(self): """Updates json-schema-v4 on this pstep (see :class:`JSchema`).""" # Lazy create it # (clients should check before`_schema_exists()`) # sdict = vars(self) jschema = sdict.get('_schema') if jschema is None: sdict['_schema'] = jschema = JSchema() return jschema def _schema_exists(self): """Always use this to avoid needless schema-instantiations.""" return '_schema' in vars(self) if __name__ == '__main__': # pragma: no cover raise NotImplementedError