11"""Utilities to get where we should write namespace pkg paths."""
22
3- EXTS = [
4- ".py" ,
5- ".pyd" ,
6- ".so" ,
7- ".pyc" ,
8- ]
3+ load ("@bazel_skylib//rules:write_file.bzl" , "write_file" )
4+
5+ _ext = struct (
6+ py = ".py" ,
7+ pyi = ".pyi" ,
8+ pyd = ".pyd" ,
9+ so = ".so" ,
10+ pyc = ".pyc" ,
11+ )
12+
13+ _INIT_CONTENTS = """\
14+ # __path__ manipulation added by bazel-contrib/rules_python to support namespace pkgs.
15+ __path__ = __import__('pkgutil').extend_path(__path__, __name__)
16+ """ .split ("\n " )
917
1018def _add_all (dirname , dirs ):
1119 dir_path = "."
1220 for dir_name in dirname .split ("/" ):
1321 dir_path = "{}/{}" .format (dir_path , dir_name )
1422 dirs [dir_path [2 :]] = None
1523
16- def _get_files (files , ignored_dirnames = [], root = None ):
24+ def get_files (* , srcs , ignored_dirnames = [], root = None ):
25+ """Get the list of filenames to write the namespace pkg files.
26+
27+ Args:
28+ srcs: {type}`src` a list of files to be passed to {bzl:obj}`py_library`
29+ as `srcs` and `data`. This is usually a result of a {obj}`glob`.
30+ ignored_dirnames: {type}`str` a list of patterns to ignore.
31+ root: {type}`str` the prefix to use as the root.
32+
33+ Returns:
34+ {type}`src` a list of paths to write the namespace pkg `__init__.py` file.
35+ """
1736 dirs = {}
1837 ignored = {i : None for i in ignored_dirnames }
1938
2039 if root :
2140 _add_all (root , ignored )
2241
23- for file in files :
42+ for file in srcs :
2443 dirname , _ , filename = file .rpartition ("/" )
2544
2645 if filename == "__init__.py" :
2746 ignored [dirname ] = None
2847 dirname , _ , _ = dirname .rpartition ("/" )
29- elif filename .endswith (EXTS [0 ]):
48+ elif filename .endswith (_ext .py ):
49+ pass
50+ elif filename .endswith (_ext .pyc ):
3051 pass
31- elif filename .endswith (EXTS [ 1 ] ):
52+ elif filename .endswith (_ext . pyd ):
3253 pass
33- elif filename .endswith (EXTS [ 2 ] ):
54+ elif filename .endswith (_ext . pyi ):
3455 pass
35- elif filename .endswith (EXTS [ 3 ] ):
56+ elif filename .endswith (_ext . so ):
3657 pass
3758 else :
3859 continue
@@ -44,6 +65,25 @@ def _get_files(files, ignored_dirnames = [], root = None):
4465
4566 return sorted ([d for d in dirs if d not in ignored ])
4667
47- namespace_pkgs = struct (
48- get_files = _get_files ,
49- )
68+ def create_inits (** kwargs ):
69+ """Create init files and return the list to be included `py_library` srcs.
70+
71+ Args:
72+ **kwargs: passed to {obj}`get_files`.
73+
74+ Returns:
75+ {type}`list[str]` to be included as part of `py_library`.
76+ """
77+ srcs = []
78+ for out in get_files (** kwargs ):
79+ src = "{}/__init__.py" .format (out )
80+ srcs .append (srcs )
81+
82+ write_file (
83+ name = "_gen_{}_namespace" .format (out ),
84+ out = src ,
85+ content = _INIT_CONTENTS ,
86+ ** kwargs
87+ )
88+
89+ return srcs
0 commit comments