This represents a path with either a specific folder name or a folder name pattern. It also may contain several compiled regex patterns for localization items (folders or files) and additional LocaleCleanerPaths that get traversed when asked to supply a list of localization items
| 51 | |
| 52 | |
| 53 | class LocaleCleanerPath: |
| 54 | """This represents a path with either a specific folder name or a folder name pattern. |
| 55 | It also may contain several compiled regex patterns for localization items (folders or files) |
| 56 | and additional LocaleCleanerPaths that get traversed when asked to supply a list of localization |
| 57 | items""" |
| 58 | |
| 59 | def __init__(self, location): |
| 60 | if location is None: |
| 61 | raise RuntimeError("location is none") |
| 62 | self.pattern = location |
| 63 | self.children = [] |
| 64 | |
| 65 | def add_child(self, child): |
| 66 | """Adds a child LocaleCleanerPath""" |
| 67 | self.children.append(child) |
| 68 | return child |
| 69 | |
| 70 | def add_path_filter(self, pre, post): |
| 71 | r"""Adds a filter consisting of a prefix and a postfix |
| 72 | (e.g. 'foobar_' and '\.qm' to match 'foobar_en_US.utf-8.qm)""" |
| 73 | try: |
| 74 | regex = re.compile('^' + pre + Locales.localepattern + post + '$') |
| 75 | except Exception as errormsg: |
| 76 | raise RuntimeError( |
| 77 | f"Malformed regex '{pre}' or '{post}': {errormsg}") from errormsg |
| 78 | self.add_child(regex) |
| 79 | |
| 80 | def get_subpaths(self, basepath): |
| 81 | """Returns direct subpaths for this object, i.e. either the named subfolder or all |
| 82 | subfolders matching the pattern""" |
| 83 | if isinstance(self.pattern, Pattern): |
| 84 | return (os.path.join(basepath, p) for p in os.listdir(basepath) |
| 85 | if self.pattern.match(p) and os.path.isdir(os.path.join(basepath, p))) |
| 86 | path = os.path.join(basepath, self.pattern) |
| 87 | return [path] if os.path.isdir(path) else [] |
| 88 | |
| 89 | def get_localizations(self, basepath): |
| 90 | """Returns all localization items for this object and all descendant objects""" |
| 91 | for path in self.get_subpaths(basepath): |
| 92 | for child in self.children: |
| 93 | if isinstance(child, LocaleCleanerPath): |
| 94 | yield from child.get_localizations(path) |
| 95 | elif isinstance(child, Pattern): |
| 96 | for element in os.listdir(path): |
| 97 | match = child.match(element) |
| 98 | if match is not None: |
| 99 | yield (match.group('locale'), |
| 100 | match.group('specifier'), |
| 101 | os.path.join(path, element)) |
| 102 | |
| 103 | |
| 104 | class Locales: |
no outgoing calls