1
+ import ast
2
+ import json
1
3
import textwrap
2
4
3
5
@@ -7,33 +9,44 @@ def iter_namespace_pkgs(namespace):
7
9
yield "." .join (parts [:i + 1 ])
8
10
9
11
10
- def build_namespace_package (tmpdir , name , version = "1.0" ):
12
+ def build_namespace_package (tmpdir , name , version = "1.0" , impl = "pkg_resources" ):
11
13
src_dir = tmpdir / name
12
14
src_dir .mkdir ()
13
15
setup_py = src_dir / 'setup.py'
14
16
namespace , _ , rest = name .rpartition ('.' )
15
17
namespaces = list (iter_namespace_pkgs (namespace ))
18
+ setup_args = {
19
+ "name" : name ,
20
+ "version" : version ,
21
+ "packages" : namespaces ,
22
+ }
23
+
24
+ if impl == "pkg_resources" :
25
+ tmpl = '__import__("pkg_resources").declare_namespace(__name__)'
26
+ setup_args ["namespace_packages" ] = namespaces
27
+ elif impl == "pkgutil" :
28
+ tmpl = '__path__ = __import__("pkgutil").extend_path(__path__, __name__)'
29
+ else :
30
+ raise ValueError (f"Cannot recognise { impl = } when creating namespaces" )
31
+
32
+ args = json .dumps (setup_args , indent = 4 )
33
+ assert ast .literal_eval (args ) # ensure it is valid Python
34
+
16
35
script = textwrap .dedent (
17
- """
36
+ """\
18
37
import setuptools
19
- setuptools.setup(
20
- name={name!r},
21
- version={version!r},
22
- namespace_packages={namespaces!r},
23
- packages={namespaces!r},
24
- )
38
+ args = {args}
39
+ setuptools.setup(**args)
25
40
"""
26
- ).format (** locals () )
41
+ ).format (args = args )
27
42
setup_py .write_text (script , encoding = 'utf-8' )
28
43
29
44
ns_pkg_dir = src_dir / namespace .replace ("." , "/" )
30
45
ns_pkg_dir .mkdir (parents = True )
31
46
32
47
for ns in namespaces :
33
48
pkg_init = src_dir / ns .replace ("." , "/" ) / '__init__.py'
34
- tmpl = '__import__("pkg_resources").declare_namespace(__name__)'
35
- decl = tmpl .format (** locals ())
36
- pkg_init .write_text (decl , encoding = 'utf-8' )
49
+ pkg_init .write_text (tmpl , encoding = 'utf-8' )
37
50
38
51
pkg_mod = ns_pkg_dir / (rest + '.py' )
39
52
some_functionality = 'name = {rest!r}' .format (** locals ())
0 commit comments