1+ import ast
2+ import json
13import textwrap
24
35
@@ -7,33 +9,44 @@ def iter_namespace_pkgs(namespace):
79 yield "." .join (parts [:i + 1 ])
810
911
10- def build_namespace_package (tmpdir , name , version = "1.0" ):
12+ def build_namespace_package (tmpdir , name , version = "1.0" , impl = "pkg_resources" ):
1113 src_dir = tmpdir / name
1214 src_dir .mkdir ()
1315 setup_py = src_dir / 'setup.py'
1416 namespace , _ , rest = name .rpartition ('.' )
1517 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+
1635 script = textwrap .dedent (
17- """
36+ """\
1837 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)
2540 """
26- ).format (** locals () )
41+ ).format (args = args )
2742 setup_py .write_text (script , encoding = 'utf-8' )
2843
2944 ns_pkg_dir = src_dir / namespace .replace ("." , "/" )
3045 ns_pkg_dir .mkdir (parents = True )
3146
3247 for ns in namespaces :
3348 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' )
3750
3851 pkg_mod = ns_pkg_dir / (rest + '.py' )
3952 some_functionality = 'name = {rest!r}' .format (** locals ())
0 commit comments