1 #!/usr/bin/python2.5 |
|
2 # |
|
3 # Copyright 2008 the Melange authors. |
|
4 # |
|
5 # Licensed under the Apache License, Version 2.0 (the "License"); |
|
6 # you may not use this file except in compliance with the License. |
|
7 # You may obtain a copy of the License at |
|
8 # |
|
9 # http://www.apache.org/licenses/LICENSE-2.0 |
|
10 # |
|
11 # Unless required by applicable law or agreed to in writing, software |
|
12 # distributed under the License is distributed on an "AS IS" BASIS, |
|
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
14 # See the License for the specific language governing permissions and |
|
15 # limitations under the License. |
|
16 |
|
17 """Path and link ID manipulation functions. |
|
18 """ |
|
19 |
|
20 __authors__ = [ |
|
21 '"Todd Larsen" <tlarsen@google.com>', |
|
22 '"Lennard de Rijk" <ljvderijk@gmail.com>', |
|
23 ] |
|
24 |
|
25 |
|
26 from soc.models import linkable |
|
27 |
|
28 |
|
29 def getPartsFromPath(path): |
|
30 """Splits path string into scope_path and link_id. |
|
31 |
|
32 Returns: |
|
33 {'scope_path': 'everything/but', |
|
34 'link_id': 'link_id'} |
|
35 or {} (empty dict) if string did not match PATH_LINK_ID_PATTERN. |
|
36 """ |
|
37 path_link_name_match = linkable.PATH_LINK_ID_REGEX.match(path) |
|
38 |
|
39 if not path_link_name_match: |
|
40 return {} |
|
41 |
|
42 return path_link_name_match.groupdict() |
|
43 |
|
44 |
|
45 def combinePath(path_parts): |
|
46 """Returns path components combined into a single string. |
|
47 |
|
48 Args: |
|
49 path_parts: a single path string, or a list of path part strings, |
|
50 or a nested list of path part strings (where the zeroeth element in |
|
51 the list is itself a list); for example: |
|
52 'a/complete/path/in/one/string' |
|
53 ['some', 'path', 'parts'] |
|
54 [['path', 'parts', 'and', 'a'], 'link ID'] |
|
55 |
|
56 Returns: |
|
57 None if path_parts is False (None, empty string, etc.) or if |
|
58 any list elements are False (an empty list, empty string, etc.); |
|
59 otherwise, the combined string with the necessary separators. |
|
60 """ |
|
61 if not path_parts: |
|
62 # completely empty input, so return early |
|
63 return None |
|
64 |
|
65 if not isinstance(path_parts, (list, tuple)): |
|
66 # a single path string, so just return it as-is (nothing to do) |
|
67 return path_parts |
|
68 |
|
69 flattened_parts = [] |
|
70 |
|
71 for part in path_parts: |
|
72 if not part: |
|
73 # encountered a "False" element, which invalidates everything else |
|
74 return None |
|
75 |
|
76 if isinstance(part, (list, tuple)): |
|
77 flattened_parts.extend(part) |
|
78 else: |
|
79 flattened_parts.append(part) |
|
80 |
|
81 return '/'.join(flattened_parts) |
|