74af2d6162cb7c39f0cb87cd54857ed042bcc3fc
[auf_recipe_django.git] / auf / recipe / django / manage.py
1 import imp
2 import sys
3
4 from django.core import management
5
6
7 def main(settings_file):
8 try:
9 mod = __import__(settings_file)
10 components = settings_file.split('.')
11 for comp in components[1:]:
12 mod = getattr(mod, comp)
13
14 except ImportError, e:
15 import sys
16 sys.stderr.write("Error loading the settings module '%s': %s"
17 % (settings_file, e))
18 return sys.exit(1)
19
20 management.execute_manager(mod)
21
22 # Fix pour le ticket Django #14087 (https://code.djangoproject.com/ticket/14087)
23 # On applique le patch https://code.djangoproject.com/attachment/ticket/14087/namespace_package_pth.diff
24 # par monkey patching.
25
26 def find_modules(name, path=None):
27 """Find all modules with name 'name'
28
29 Unlike find_module in the imp package this returns a list of all
30 matched modules.
31 """
32 results = []
33 if path is None: path = sys.path
34 for p in path:
35 importer = sys.path_importer_cache.get(p, None)
36 if importer is None:
37 find_module = imp.find_module
38 else:
39 find_module = importer.find_module
40
41 try:
42 result = find_module(name, [p])
43 if result is not None:
44 results.append(result)
45 except ImportError:
46 pass
47 if not results:
48 raise ImportError("No module named %.200s" % name)
49 return results
50
51 def find_management_module(app_name):
52 """
53 Determines the path to the management module for the given app_name,
54 without actually importing the application or the management module.
55
56 Raises ImportError if the management module cannot be found for any reason.
57 """
58 parts = app_name.split('.')
59
60 for i in range(len(parts), 0, -1):
61 try:
62 paths = sys.modules['.'.join(parts[:i])].__path__
63 except KeyError:
64 continue
65
66 parts = parts[i:] + ['management']
67 parts.reverse()
68 break
69 else:
70 parts.append('management')
71 parts.reverse()
72 part = parts.pop()
73 paths = None
74
75 # When using manage.py, the project module is added to the path,
76 # loaded, then removed from the path. This means that
77 # testproject.testapp.models can be loaded in future, even if
78 # testproject isn't in the path. When looking for the management
79 # module, we need look for the case where the project name is part
80 # of the app_name but the project directory itself isn't on the path.
81 try:
82 modules = find_modules(part, paths)
83 paths = [m[1] for m in modules]
84 except ImportError,e:
85 if os.path.basename(os.getcwd()) != part:
86 raise e
87
88 while parts:
89 part = parts.pop()
90 modules = find_modules(part, paths)
91 paths = [m[1] for m in modules]
92 return paths[0]
93
94 # Patch!
95 management.find_management_module = find_management_module