django-cfg 1.4.9__py3-none-any.whl → 1.4.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. django_cfg/apps/agents/management/commands/create_agent.py +1 -1
  2. django_cfg/apps/agents/management/commands/orchestrator_status.py +3 -3
  3. django_cfg/apps/newsletter/serializers.py +40 -3
  4. django_cfg/apps/newsletter/views/campaigns.py +12 -3
  5. django_cfg/apps/newsletter/views/emails.py +14 -3
  6. django_cfg/apps/newsletter/views/subscriptions.py +12 -2
  7. django_cfg/apps/payments/middleware/api_access.py +6 -2
  8. django_cfg/apps/payments/middleware/rate_limiting.py +2 -1
  9. django_cfg/apps/payments/middleware/usage_tracking.py +5 -1
  10. django_cfg/apps/payments/models/managers/api_key_managers.py +0 -1
  11. django_cfg/apps/payments/models/managers/subscription_managers.py +0 -1
  12. django_cfg/apps/payments/services/core/balance_service.py +5 -5
  13. django_cfg/apps/payments/services/core/subscription_service.py +1 -2
  14. django_cfg/apps/payments/views/api/balances.py +8 -7
  15. django_cfg/apps/payments/views/api/base.py +10 -6
  16. django_cfg/apps/payments/views/api/currencies.py +53 -10
  17. django_cfg/apps/payments/views/api/payments.py +3 -1
  18. django_cfg/apps/payments/views/api/subscriptions.py +2 -5
  19. django_cfg/apps/payments/views/api/webhooks.py +72 -7
  20. django_cfg/apps/payments/views/overview/serializers.py +34 -1
  21. django_cfg/apps/payments/views/overview/views.py +2 -1
  22. django_cfg/apps/payments/views/serializers/payments.py +6 -6
  23. django_cfg/apps/urls.py +106 -45
  24. django_cfg/core/base/config_model.py +2 -2
  25. django_cfg/core/constants.py +1 -1
  26. django_cfg/core/generation/integration_generators/__init__.py +1 -1
  27. django_cfg/core/generation/integration_generators/api.py +82 -41
  28. django_cfg/core/integration/display/startup.py +30 -22
  29. django_cfg/core/integration/url_integration.py +15 -16
  30. django_cfg/dashboard/sections/documentation.py +391 -0
  31. django_cfg/management/commands/check_endpoints.py +11 -160
  32. django_cfg/management/commands/check_settings.py +13 -265
  33. django_cfg/management/commands/clear_constance.py +13 -201
  34. django_cfg/management/commands/create_token.py +13 -321
  35. django_cfg/management/commands/generate_clients.py +23 -0
  36. django_cfg/management/commands/list_urls.py +13 -306
  37. django_cfg/management/commands/migrate_all.py +13 -126
  38. django_cfg/management/commands/migrator.py +13 -396
  39. django_cfg/management/commands/rundramatiq.py +15 -247
  40. django_cfg/management/commands/rundramatiq_simulator.py +12 -429
  41. django_cfg/management/commands/runserver_ngrok.py +15 -160
  42. django_cfg/management/commands/script.py +12 -488
  43. django_cfg/management/commands/show_config.py +12 -215
  44. django_cfg/management/commands/show_urls.py +12 -342
  45. django_cfg/management/commands/superuser.py +15 -295
  46. django_cfg/management/commands/task_clear.py +14 -217
  47. django_cfg/management/commands/task_status.py +13 -248
  48. django_cfg/management/commands/test_email.py +15 -86
  49. django_cfg/management/commands/test_telegram.py +14 -61
  50. django_cfg/management/commands/test_twilio.py +15 -105
  51. django_cfg/management/commands/tree.py +13 -383
  52. django_cfg/management/commands/validate_openapi.py +10 -0
  53. django_cfg/middleware/README.md +1 -1
  54. django_cfg/middleware/user_activity.py +3 -3
  55. django_cfg/models/__init__.py +2 -2
  56. django_cfg/models/api/drf/spectacular.py +6 -6
  57. django_cfg/models/django/__init__.py +2 -2
  58. django_cfg/models/django/openapi.py +238 -0
  59. django_cfg/models/django/{revolution.py → revolution_legacy.py} +8 -0
  60. django_cfg/modules/django_admin/management/__init__.py +0 -0
  61. django_cfg/modules/django_admin/management/commands/__init__.py +0 -0
  62. django_cfg/modules/django_admin/management/commands/check_endpoints.py +169 -0
  63. django_cfg/modules/django_admin/management/commands/check_settings.py +355 -0
  64. django_cfg/modules/django_admin/management/commands/clear_constance.py +208 -0
  65. django_cfg/modules/django_admin/management/commands/create_token.py +328 -0
  66. django_cfg/modules/django_admin/management/commands/list_urls.py +313 -0
  67. django_cfg/modules/django_admin/management/commands/migrate_all.py +133 -0
  68. django_cfg/modules/django_admin/management/commands/migrator.py +403 -0
  69. django_cfg/modules/django_admin/management/commands/script.py +496 -0
  70. django_cfg/modules/django_admin/management/commands/show_config.py +225 -0
  71. django_cfg/modules/django_admin/management/commands/show_urls.py +361 -0
  72. django_cfg/modules/django_admin/management/commands/superuser.py +302 -0
  73. django_cfg/modules/django_admin/management/commands/tree.py +390 -0
  74. django_cfg/modules/django_client/__init__.py +20 -0
  75. django_cfg/modules/django_client/apps.py +35 -0
  76. django_cfg/modules/django_client/core/__init__.py +56 -0
  77. django_cfg/modules/django_client/core/archive/__init__.py +11 -0
  78. django_cfg/modules/django_client/core/archive/manager.py +134 -0
  79. django_cfg/modules/django_client/core/cli/__init__.py +12 -0
  80. django_cfg/modules/django_client/core/cli/main.py +235 -0
  81. django_cfg/modules/django_client/core/config/__init__.py +18 -0
  82. django_cfg/modules/django_client/core/config/config.py +188 -0
  83. django_cfg/modules/django_client/core/config/group.py +101 -0
  84. django_cfg/modules/django_client/core/config/service.py +209 -0
  85. django_cfg/modules/django_client/core/generator/__init__.py +115 -0
  86. django_cfg/modules/django_client/core/generator/base.py +767 -0
  87. django_cfg/modules/django_client/core/generator/python.py +751 -0
  88. django_cfg/modules/django_client/core/generator/templates/python/__init__.py.jinja +9 -0
  89. django_cfg/modules/django_client/core/generator/templates/python/api_wrapper.py.jinja +130 -0
  90. django_cfg/modules/django_client/core/generator/templates/python/app_init.py.jinja +6 -0
  91. django_cfg/modules/django_client/core/generator/templates/python/client/app_client.py.jinja +18 -0
  92. django_cfg/modules/django_client/core/generator/templates/python/client/flat_client.py.jinja +38 -0
  93. django_cfg/modules/django_client/core/generator/templates/python/client/main_client.py.jinja +50 -0
  94. django_cfg/modules/django_client/core/generator/templates/python/client/main_client_file.py.jinja +13 -0
  95. django_cfg/modules/django_client/core/generator/templates/python/client/operation_method.py.jinja +7 -0
  96. django_cfg/modules/django_client/core/generator/templates/python/client/sub_client.py.jinja +11 -0
  97. django_cfg/modules/django_client/core/generator/templates/python/client_file.py.jinja +13 -0
  98. django_cfg/modules/django_client/core/generator/templates/python/main_init.py.jinja +50 -0
  99. django_cfg/modules/django_client/core/generator/templates/python/models/app_models.py.jinja +17 -0
  100. django_cfg/modules/django_client/core/generator/templates/python/models/enum_class.py.jinja +15 -0
  101. django_cfg/modules/django_client/core/generator/templates/python/models/enums.py.jinja +8 -0
  102. django_cfg/modules/django_client/core/generator/templates/python/models/models.py.jinja +17 -0
  103. django_cfg/modules/django_client/core/generator/templates/python/models/schema_class.py.jinja +19 -0
  104. django_cfg/modules/django_client/core/generator/templates/python/utils/logger.py.jinja +255 -0
  105. django_cfg/modules/django_client/core/generator/templates/python/utils/schema.py.jinja +12 -0
  106. django_cfg/modules/django_client/core/generator/templates/typescript/app_index.ts.jinja +2 -0
  107. django_cfg/modules/django_client/core/generator/templates/typescript/client/app_client.ts.jinja +18 -0
  108. django_cfg/modules/django_client/core/generator/templates/typescript/client/client.ts.jinja +327 -0
  109. django_cfg/modules/django_client/core/generator/templates/typescript/client/flat_client.ts.jinja +109 -0
  110. django_cfg/modules/django_client/core/generator/templates/typescript/client/main_client_file.ts.jinja +9 -0
  111. django_cfg/modules/django_client/core/generator/templates/typescript/client/operation.ts.jinja +61 -0
  112. django_cfg/modules/django_client/core/generator/templates/typescript/client/sub_client.ts.jinja +15 -0
  113. django_cfg/modules/django_client/core/generator/templates/typescript/client_file.ts.jinja +9 -0
  114. django_cfg/modules/django_client/core/generator/templates/typescript/index.ts.jinja +5 -0
  115. django_cfg/modules/django_client/core/generator/templates/typescript/main_index.ts.jinja +206 -0
  116. django_cfg/modules/django_client/core/generator/templates/typescript/models/app_models.ts.jinja +8 -0
  117. django_cfg/modules/django_client/core/generator/templates/typescript/models/enums.ts.jinja +4 -0
  118. django_cfg/modules/django_client/core/generator/templates/typescript/models/models.ts.jinja +8 -0
  119. django_cfg/modules/django_client/core/generator/templates/typescript/utils/errors.ts.jinja +114 -0
  120. django_cfg/modules/django_client/core/generator/templates/typescript/utils/http.ts.jinja +98 -0
  121. django_cfg/modules/django_client/core/generator/templates/typescript/utils/logger.ts.jinja +251 -0
  122. django_cfg/modules/django_client/core/generator/templates/typescript/utils/schema.ts.jinja +7 -0
  123. django_cfg/modules/django_client/core/generator/templates/typescript/utils/storage.ts.jinja +114 -0
  124. django_cfg/modules/django_client/core/generator/typescript.py +872 -0
  125. django_cfg/modules/django_client/core/groups/__init__.py +13 -0
  126. django_cfg/modules/django_client/core/groups/detector.py +178 -0
  127. django_cfg/modules/django_client/core/groups/manager.py +314 -0
  128. django_cfg/modules/django_client/core/ir/__init__.py +57 -0
  129. django_cfg/modules/django_client/core/ir/context.py +387 -0
  130. django_cfg/modules/django_client/core/ir/operation.py +518 -0
  131. django_cfg/modules/django_client/core/ir/schema.py +353 -0
  132. django_cfg/modules/django_client/core/parser/__init__.py +74 -0
  133. django_cfg/modules/django_client/core/parser/base.py +648 -0
  134. django_cfg/modules/django_client/core/parser/models/__init__.py +74 -0
  135. django_cfg/modules/django_client/core/parser/models/base.py +212 -0
  136. django_cfg/modules/django_client/core/parser/models/components.py +160 -0
  137. django_cfg/modules/django_client/core/parser/models/openapi.py +203 -0
  138. django_cfg/modules/django_client/core/parser/models/operation.py +207 -0
  139. django_cfg/modules/django_client/core/parser/models/schema.py +266 -0
  140. django_cfg/modules/django_client/core/parser/openapi30.py +56 -0
  141. django_cfg/modules/django_client/core/parser/openapi31.py +64 -0
  142. django_cfg/modules/django_client/core/validation/__init__.py +22 -0
  143. django_cfg/modules/django_client/core/validation/checker.py +134 -0
  144. django_cfg/modules/django_client/core/validation/fixer.py +216 -0
  145. django_cfg/modules/django_client/core/validation/reporter.py +480 -0
  146. django_cfg/modules/django_client/core/validation/rules/__init__.py +11 -0
  147. django_cfg/modules/django_client/core/validation/rules/base.py +96 -0
  148. django_cfg/modules/django_client/core/validation/rules/type_hints.py +288 -0
  149. django_cfg/modules/django_client/core/validation/safety.py +266 -0
  150. django_cfg/modules/django_client/management/__init__.py +3 -0
  151. django_cfg/modules/django_client/management/commands/__init__.py +3 -0
  152. django_cfg/modules/django_client/management/commands/generate_client.py +422 -0
  153. django_cfg/modules/django_client/management/commands/validate_openapi.py +343 -0
  154. django_cfg/modules/django_client/spectacular/__init__.py +9 -0
  155. django_cfg/modules/django_client/spectacular/enum_naming.py +192 -0
  156. django_cfg/modules/django_client/urls.py +72 -0
  157. django_cfg/modules/django_email/management/__init__.py +0 -0
  158. django_cfg/modules/django_email/management/commands/__init__.py +0 -0
  159. django_cfg/modules/django_email/management/commands/test_email.py +93 -0
  160. django_cfg/modules/django_logging/django_logger.py +6 -6
  161. django_cfg/modules/django_ngrok/management/__init__.py +0 -0
  162. django_cfg/modules/django_ngrok/management/commands/__init__.py +0 -0
  163. django_cfg/modules/django_ngrok/management/commands/runserver_ngrok.py +167 -0
  164. django_cfg/modules/django_tasks/management/__init__.py +0 -0
  165. django_cfg/modules/django_tasks/management/commands/__init__.py +0 -0
  166. django_cfg/modules/django_tasks/management/commands/rundramatiq.py +254 -0
  167. django_cfg/modules/django_tasks/management/commands/rundramatiq_simulator.py +437 -0
  168. django_cfg/modules/django_tasks/management/commands/task_clear.py +226 -0
  169. django_cfg/modules/django_tasks/management/commands/task_status.py +257 -0
  170. django_cfg/modules/django_telegram/management/__init__.py +0 -0
  171. django_cfg/modules/django_telegram/management/commands/__init__.py +0 -0
  172. django_cfg/modules/django_telegram/management/commands/test_telegram.py +68 -0
  173. django_cfg/modules/django_twilio/management/__init__.py +0 -0
  174. django_cfg/modules/django_twilio/management/commands/__init__.py +0 -0
  175. django_cfg/modules/django_twilio/management/commands/test_twilio.py +112 -0
  176. django_cfg/modules/django_unfold/callbacks/main.py +16 -5
  177. django_cfg/modules/django_unfold/callbacks/revolution.py +41 -36
  178. django_cfg/modules/django_unfold/dashboard.py +1 -1
  179. django_cfg/pyproject.toml +2 -6
  180. django_cfg/registry/third_party.py +5 -7
  181. django_cfg/routing/callbacks.py +1 -1
  182. django_cfg/static/admin/css/prose-unfold.css +666 -0
  183. django_cfg/templates/admin/index.html +8 -0
  184. django_cfg/templates/admin/index_new.html +13 -0
  185. django_cfg/templates/admin/layouts/dashboard_with_tabs.html +15 -3
  186. django_cfg/templates/admin/sections/documentation_section.html +172 -0
  187. django_cfg/templates/admin/snippets/tabs/documentation_tab.html +231 -0
  188. {django_cfg-1.4.9.dist-info → django_cfg-1.4.11.dist-info}/METADATA +2 -2
  189. {django_cfg-1.4.9.dist-info → django_cfg-1.4.11.dist-info}/RECORD +192 -71
  190. django_cfg/management/commands/generate.py +0 -107
  191. {django_cfg-1.4.9.dist-info → django_cfg-1.4.11.dist-info}/WHEEL +0 -0
  192. {django_cfg-1.4.9.dist-info → django_cfg-1.4.11.dist-info}/entry_points.txt +0 -0
  193. {django_cfg-1.4.9.dist-info → django_cfg-1.4.11.dist-info}/licenses/LICENSE +0 -0
@@ -160,8 +160,8 @@ class StartupDisplayManager(BaseDisplayManager):
160
160
  # App-specific configuration panels
161
161
  self._display_config_panels()
162
162
 
163
- # Revolution info
164
- self._display_revolution_info()
163
+ # OpenAPI Client info
164
+ self._display_openapi_client_info()
165
165
 
166
166
  # Management commands
167
167
  self._display_commands_info()
@@ -661,30 +661,38 @@ class StartupDisplayManager(BaseDisplayManager):
661
661
  print(f"❌ ERROR in _display_constance_summary: {e}")
662
662
  traceback.print_exc()
663
663
 
664
- def _display_revolution_info(self):
665
- """Display Django Revolution information."""
664
+ def _display_openapi_client_info(self):
665
+ """Display Django Client (OpenAPI) information."""
666
666
  try:
667
- from django_revolution import get_revolution_info
668
- revolution_info = get_revolution_info()
669
-
670
- revolution_table = self.create_table()
671
- revolution_table.add_column("Setting", style="cyan", width=30)
672
- revolution_table.add_column("Value", style="white")
673
-
674
- revolution_table.add_row("📦 Version", revolution_info.get('version', 'unknown'))
675
- revolution_table.add_row("📊 Zones", str(revolution_info.get('zones_count', 0)))
676
- revolution_table.add_row("📱 Apps", str(revolution_info.get('apps_count', 0)))
677
- revolution_table.add_row("🔗 API Prefix", revolution_info.get('api_prefix', '/api/'))
678
-
679
- revolution_panel = self.create_panel(
680
- revolution_table,
681
- title="🚀 Django Revolution",
667
+ from django_cfg.modules.django_client.core.config.service import DjangoOpenAPI
668
+
669
+ service = DjangoOpenAPI.instance()
670
+ if not service.config or not service.config.enabled:
671
+ return
672
+
673
+ openapi_table = self.create_table()
674
+ openapi_table.add_column("Setting", style="cyan", width=30)
675
+ openapi_table.add_column("Value", style="white")
676
+
677
+ openapi_table.add_row("📦 Status", "[green]Enabled[/green]")
678
+ openapi_table.add_row("📊 Groups", str(len(service.config.groups)))
679
+ openapi_table.add_row("🔗 API Prefix", f"/{service.config.api_prefix}/")
680
+ openapi_table.add_row("📁 Output Dir", str(service.config.output_dir))
681
+
682
+ # List groups
683
+ group_names = [g.name for g in service.config.groups]
684
+ if group_names:
685
+ openapi_table.add_row("🏷️ Groups", ", ".join(group_names[:3]) + ("..." if len(group_names) > 3 else ""))
686
+
687
+ openapi_panel = self.create_panel(
688
+ openapi_table,
689
+ title="🚀 Django Client (OpenAPI)",
682
690
  border_style="blue"
683
691
  )
684
-
685
- self.console.print(revolution_panel)
692
+
693
+ self.console.print(openapi_panel)
686
694
  except ImportError:
687
- # Django Revolution not available
695
+ # Django Client not available
688
696
  pass
689
697
  except Exception:
690
698
  pass
@@ -16,7 +16,7 @@ def add_django_cfg_urls(urlpatterns: List[URLPattern], cfg_prefix: str = "cfg/")
16
16
 
17
17
  This function adds:
18
18
  - Django CFG management URLs (cfg/)
19
- - Django Revolution URLs (if available)
19
+ - Django Client URLs (if available)
20
20
  - Startup information display (based on config)
21
21
 
22
22
  Args:
@@ -37,22 +37,16 @@ def add_django_cfg_urls(urlpatterns: List[URLPattern], cfg_prefix: str = "cfg/")
37
37
 
38
38
  # Automatically adds:
39
39
  # - path("cfg/", include("django_cfg.apps.urls"))
40
- # - Django Revolution URLs (if available)
40
+ # - Django Client URLs (if available)
41
41
  # - Startup info display (based on config.startup_info_mode)
42
42
  urlpatterns = add_django_cfg_urls(urlpatterns)
43
43
  """
44
44
  # Add django_cfg API URLs
45
+ # Note: Django Client URLs are included in django_cfg.apps.urls
46
+ # at /cfg/openapi/{group}/schema/ to avoid conflicts
45
47
  new_patterns = urlpatterns + [
46
48
  path(cfg_prefix, include("django_cfg.apps.urls")),
47
49
  ]
48
-
49
- # Try to add Django Revolution URLs if available
50
- try:
51
- from django_revolution import add_revolution_urls
52
- new_patterns = add_revolution_urls(new_patterns)
53
- except ImportError:
54
- # Django Revolution not available - skip
55
- pass
56
50
 
57
51
  # Add django-browser-reload URLs in development (if installed)
58
52
  if settings.DEBUG:
@@ -122,13 +116,18 @@ def get_django_cfg_urls_info() -> dict:
122
116
  }
123
117
  }
124
118
 
125
- # Add Django Revolution info if available
119
+ # Add Django Client info if available
126
120
  try:
127
- from django_revolution import get_revolution_urls_info
128
- revolution_info = get_revolution_urls_info()
129
- if revolution_info:
130
- info["django_revolution"] = revolution_info
121
+ from django_cfg.modules.django_client.core.config.service import DjangoOpenAPI
122
+ service = DjangoOpenAPI.instance()
123
+ if service.config and service.config.enabled:
124
+ info["django_client"] = {
125
+ "enabled": True,
126
+ "groups": len(service.config.groups),
127
+ "base_url": service.config.base_url,
128
+ "output_dir": service.config.output_dir,
129
+ }
131
130
  except ImportError:
132
131
  pass
133
-
132
+
134
133
  return info
@@ -0,0 +1,391 @@
1
+ """Documentation section for dashboard."""
2
+
3
+ import os
4
+ import inspect
5
+ from pathlib import Path
6
+ from typing import Dict, Any, List
7
+ from django.core.management import get_commands, load_command_class
8
+ from .base import DataSection
9
+
10
+
11
+ class DocumentationSection(DataSection):
12
+ """
13
+ Management commands documentation section.
14
+
15
+ Displays the README.md file from django_cfg/management/ directory.
16
+ """
17
+
18
+ template_name = "admin/sections/documentation_section.html"
19
+ title = "Commands Documentation"
20
+ icon = "description"
21
+
22
+ def get_context_data(self, **kwargs) -> Dict[str, Any]:
23
+ """Add documentation data directly to context (not nested under 'data')."""
24
+ # Call parent but skip DataSection's get_data() nesting
25
+ context = super(DataSection, self).get_context_data(**kwargs)
26
+ # Add our data directly to context
27
+ context.update(self.get_data())
28
+ return context
29
+
30
+ def find_module_readme(self, module_name: str) -> str:
31
+ """Find and read README.md from module's management directory."""
32
+ import logging
33
+ logger = logging.getLogger(__name__)
34
+
35
+ try:
36
+ import django_cfg
37
+ django_cfg_path = Path(django_cfg.__file__).parent
38
+
39
+ # Try different paths
40
+ possible_paths = [
41
+ django_cfg_path / 'modules' / module_name / 'management' / 'README.md',
42
+ django_cfg_path / 'management' / 'commands' / module_name / 'README.md',
43
+ ]
44
+
45
+ for readme_path in possible_paths:
46
+ if readme_path.exists():
47
+ logger.info(f"Found module README at: {readme_path}")
48
+ with open(readme_path, 'r', encoding='utf-8') as f:
49
+ return f.read()
50
+ except Exception as e:
51
+ logger.debug(f"Could not find README for module {module_name}: {e}")
52
+
53
+ return ""
54
+
55
+ def get_commands_structure(self) -> Dict[str, List[Dict[str, Any]]]:
56
+ """Get structured command data grouped by app."""
57
+ import logging
58
+ logger = logging.getLogger(__name__)
59
+
60
+ # Get all management commands
61
+ commands = get_commands()
62
+
63
+ # Filter only django_cfg commands
64
+ django_cfg_commands = {
65
+ name: app for name, app in commands.items()
66
+ if 'django_cfg' in app
67
+ }
68
+
69
+ logger.info(f"Found {len(django_cfg_commands)} django_cfg commands")
70
+
71
+ # Group commands by app
72
+ commands_by_app = {}
73
+
74
+ for cmd_name, app_name in sorted(django_cfg_commands.items()):
75
+ try:
76
+ # Load the command class
77
+ try:
78
+ command = load_command_class(app_name, cmd_name)
79
+ except (ImportError, ModuleNotFoundError) as e:
80
+ logger.debug(f"Skipping command {cmd_name}: module not found - {e}")
81
+ continue
82
+
83
+ # Use app_name as group key
84
+ if app_name not in commands_by_app:
85
+ # Create display name from app_name
86
+ display_name = app_name.replace('django_cfg.modules.', '').replace('django_cfg', 'Django CFG').replace('_', ' ').title()
87
+
88
+ commands_by_app[app_name] = {
89
+ 'name': app_name,
90
+ 'display_name': display_name,
91
+ 'commands': []
92
+ }
93
+
94
+ # Extract command information
95
+ command_info = {
96
+ 'name': cmd_name,
97
+ 'help': getattr(command, 'help', 'No description available'),
98
+ 'docstring': inspect.cleandoc(command.__doc__) if command.__doc__ else '',
99
+ 'web_executable': getattr(command, 'web_executable', None),
100
+ 'requires_input': getattr(command, 'requires_input', None),
101
+ 'is_destructive': getattr(command, 'is_destructive', None),
102
+ 'arguments': []
103
+ }
104
+
105
+ # Get arguments
106
+ try:
107
+ parser = command.create_parser('', cmd_name)
108
+ actions = [action for action in parser._actions if action.dest != 'help']
109
+
110
+ for action in actions:
111
+ if action.option_strings:
112
+ command_info['arguments'].append({
113
+ 'options': action.option_strings,
114
+ 'help': action.help or 'No description',
115
+ 'default': action.default if action.default != '==SUPPRESS==' else None,
116
+ 'required': getattr(action, 'required', False),
117
+ })
118
+ except Exception as e:
119
+ logger.debug(f"Could not extract arguments for {cmd_name}: {e}")
120
+
121
+ commands_by_app[app_name]['commands'].append(command_info)
122
+
123
+ except Exception as e:
124
+ logger.error(f"Error loading command {cmd_name}: {e}")
125
+ continue
126
+
127
+ return commands_by_app
128
+
129
+ def generate_documentation_from_commands(self) -> str:
130
+ """Generate markdown documentation from command docstrings and module READMEs."""
131
+ import logging
132
+ logger = logging.getLogger(__name__)
133
+
134
+ markdown_lines = []
135
+ markdown_lines.append("# Django-CFG Management Commands\n\n")
136
+
137
+ # Check for main README.md
138
+ try:
139
+ import django_cfg
140
+ django_cfg_path = Path(django_cfg.__file__).parent
141
+ main_readme_path = django_cfg_path / 'management' / 'README.md'
142
+
143
+ if main_readme_path.exists():
144
+ logger.info("Found main management README.md, using it as primary documentation")
145
+ with open(main_readme_path, 'r', encoding='utf-8') as f:
146
+ return f.read() # Use existing README if it exists
147
+ except Exception as e:
148
+ logger.debug(f"No main README found, continuing with auto-generation: {e}")
149
+
150
+ markdown_lines.append("_Auto-generated documentation from command docstrings and module READMEs._\n\n")
151
+
152
+ # Get all management commands
153
+ commands = get_commands()
154
+
155
+ # Filter only django_cfg commands
156
+ django_cfg_commands = {
157
+ name: app for name, app in commands.items()
158
+ if 'django_cfg' in app
159
+ }
160
+
161
+ logger.info(f"Found {len(django_cfg_commands)} django_cfg commands")
162
+
163
+ # Group commands by module
164
+ commands_by_module = {}
165
+ module_paths = {} # Store module paths for README lookup
166
+
167
+ for cmd_name, app_name in sorted(django_cfg_commands.items()):
168
+ try:
169
+ # Load the command class
170
+ command = load_command_class(app_name, cmd_name)
171
+
172
+ # Get module path
173
+ module_path = command.__module__
174
+ if 'modules' in module_path:
175
+ # Extract module name like 'django_ngrok', 'django_tasks', etc.
176
+ parts = module_path.split('.')
177
+ if 'modules' in parts:
178
+ module_idx = parts.index('modules')
179
+ if len(parts) > module_idx + 1:
180
+ module_name = parts[module_idx + 1]
181
+ else:
182
+ module_name = 'core'
183
+ else:
184
+ module_name = 'core'
185
+ else:
186
+ module_name = 'core'
187
+
188
+ if module_name not in commands_by_module:
189
+ commands_by_module[module_name] = []
190
+ module_paths[module_name] = module_path
191
+
192
+ commands_by_module[module_name].append((cmd_name, command))
193
+
194
+ except Exception as e:
195
+ logger.error(f"Error loading command {cmd_name}: {e}")
196
+ continue
197
+
198
+ # Generate documentation for each module
199
+ for module_name in sorted(commands_by_module.keys()):
200
+ markdown_lines.append(f"\n## {module_name.replace('_', ' ').title()} Commands\n\n")
201
+
202
+ # Check for module-specific README
203
+ module_readme = self.find_module_readme(module_name)
204
+ if module_readme:
205
+ markdown_lines.append(f"_{module_name} module documentation:_\n\n")
206
+ markdown_lines.append(module_readme)
207
+ markdown_lines.append("\n\n### Available Commands\n\n")
208
+
209
+ for cmd_name, command_class in sorted(commands_by_module[module_name]):
210
+ markdown_lines.append(f"\n#### `{cmd_name}`\n\n")
211
+
212
+ # Get help text
213
+ if hasattr(command_class, 'help'):
214
+ markdown_lines.append(f"{command_class.help}\n\n")
215
+
216
+ # Get class docstring
217
+ if command_class.__doc__:
218
+ doc = inspect.cleandoc(command_class.__doc__)
219
+ markdown_lines.append(f"{doc}\n\n")
220
+
221
+ # Get metadata
222
+ metadata = []
223
+ if hasattr(command_class, 'web_executable'):
224
+ metadata.append(f"**Web Executable**: {'Yes' if command_class.web_executable else 'No'}")
225
+ if hasattr(command_class, 'requires_input'):
226
+ metadata.append(f"**Requires Input**: {'Yes' if command_class.requires_input else 'No'}")
227
+ if hasattr(command_class, 'is_destructive'):
228
+ metadata.append(f"**Destructive**: {'Yes' if command_class.is_destructive else 'No'}")
229
+
230
+ if metadata:
231
+ markdown_lines.append("**Metadata:**\n\n")
232
+ for meta in metadata:
233
+ markdown_lines.append(f"- {meta}\n")
234
+ markdown_lines.append("\n")
235
+
236
+ # Get arguments
237
+ try:
238
+ parser = command_class.create_parser('', cmd_name)
239
+ actions = [action for action in parser._actions if action.dest != 'help']
240
+
241
+ if actions:
242
+ markdown_lines.append("**Arguments:**\n\n")
243
+ for action in actions:
244
+ if action.option_strings:
245
+ opts = ', '.join(f"`{opt}`" for opt in action.option_strings)
246
+ help_text = action.help or 'No description'
247
+ markdown_lines.append(f"- {opts}: {help_text}\n")
248
+ markdown_lines.append("\n")
249
+ except Exception as e:
250
+ logger.debug(f"Could not extract arguments for {cmd_name}: {e}")
251
+
252
+ # Add usage example if available in docstring
253
+ if command_class.__doc__ and '```' in command_class.__doc__:
254
+ markdown_lines.append("**Example:**\n\n")
255
+
256
+ return ''.join(markdown_lines)
257
+
258
+ def get_data(self) -> Dict[str, Any]:
259
+ """Get structured command documentation data."""
260
+ import logging
261
+ logger = logging.getLogger(__name__)
262
+
263
+ try:
264
+ commands_structure = self.get_commands_structure()
265
+
266
+ return {
267
+ 'commands_by_module': commands_structure,
268
+ 'total_commands': sum(len(app['commands']) for app in commands_structure.values()),
269
+ 'total_modules': len(commands_structure),
270
+ }
271
+ except Exception as e:
272
+ logger.error(f"Error generating command structure: {e}", exc_info=True)
273
+ return {
274
+ 'commands_by_module': {},
275
+ 'total_commands': 0,
276
+ 'total_modules': 0,
277
+ 'error': str(e)
278
+ }
279
+
280
+ def get_data_old(self) -> Dict[str, Any]:
281
+ """DEPRECATED: Get documentation content from README.md or auto-generate from docstrings."""
282
+ import logging
283
+ logger = logging.getLogger(__name__)
284
+
285
+ # Check if we should use auto-generation
286
+ use_autogen = os.environ.get('DJANGO_CFG_AUTOGEN_DOCS', 'true').lower() == 'true'
287
+
288
+ readme_content = ""
289
+ documentation_html = ""
290
+ readme_path = None
291
+ readme_exists = False
292
+
293
+ if use_autogen:
294
+ # Auto-generate documentation from command docstrings
295
+ logger.info("Auto-generating documentation from command docstrings")
296
+ try:
297
+ readme_content = self.generate_documentation_from_commands()
298
+
299
+ # Convert to HTML
300
+ try:
301
+ import markdown
302
+ documentation_html = markdown.markdown(
303
+ readme_content,
304
+ extensions=[
305
+ 'markdown.extensions.fenced_code',
306
+ 'markdown.extensions.tables',
307
+ 'markdown.extensions.toc',
308
+ 'markdown.extensions.nl2br',
309
+ 'markdown.extensions.sane_lists',
310
+ ]
311
+ )
312
+ logger.info("Auto-generated documentation rendered successfully")
313
+ except ImportError:
314
+ logger.warning("Markdown library not available, will display as plain text")
315
+
316
+ readme_exists = True
317
+ readme_path = "Auto-generated from docstrings"
318
+
319
+ except Exception as e:
320
+ logger.error(f"Error auto-generating documentation: {e}", exc_info=True)
321
+ readme_content = f"Error auto-generating documentation: {str(e)}"
322
+ else:
323
+ # Use static README.md file
324
+ # Try multiple path resolution strategies
325
+ possible_paths = [
326
+ # Strategy 1: Relative to this file
327
+ Path(__file__).parent.parent.parent / 'management' / 'README.md',
328
+ # Strategy 2: Using django_cfg module location
329
+ Path(__file__).parent.parent.parent / 'management' / 'README.md',
330
+ # Strategy 3: Absolute path for django_cfg package
331
+ Path('/Users/markinmatrix/Documents/htdocs/@CARAPIS/encar_parser_new/@projects/django-cfg/projects/django-cfg-dev/src/django_cfg/management/README.md'),
332
+ ]
333
+
334
+ # Find the first existing path
335
+ for path in possible_paths:
336
+ if path.exists():
337
+ readme_path = path
338
+ logger.info(f"Found README.md at: {readme_path}")
339
+ break
340
+
341
+ # If still not found, try using django_cfg module import
342
+ if not readme_path or not readme_path.exists():
343
+ try:
344
+ import django_cfg
345
+ django_cfg_path = Path(django_cfg.__file__).parent
346
+ readme_path = django_cfg_path / 'management' / 'README.md'
347
+ logger.info(f"Using django_cfg module path: {readme_path}")
348
+ except Exception as e:
349
+ logger.error(f"Error finding django_cfg module: {e}")
350
+ readme_path = possible_paths[0] # Fallback to first path
351
+
352
+ try:
353
+ if readme_path and readme_path.exists():
354
+ logger.info(f"Reading README from: {readme_path}")
355
+ with open(readme_path, 'r', encoding='utf-8') as f:
356
+ readme_content = f.read()
357
+ logger.info(f"README content loaded: {len(readme_content)} characters")
358
+
359
+ # Try to convert markdown to HTML
360
+ try:
361
+ import markdown
362
+ documentation_html = markdown.markdown(
363
+ readme_content,
364
+ extensions=[
365
+ 'markdown.extensions.fenced_code',
366
+ 'markdown.extensions.tables',
367
+ 'markdown.extensions.toc',
368
+ 'markdown.extensions.nl2br',
369
+ 'markdown.extensions.sane_lists',
370
+ ]
371
+ )
372
+ logger.info("Markdown rendered successfully")
373
+ except ImportError:
374
+ logger.warning("Markdown library not available, will display as plain text")
375
+ pass
376
+
377
+ readme_exists = True
378
+ else:
379
+ logger.error(f"README.md not found at: {readme_path}")
380
+ readme_content = f"README.md not found. Searched paths:\n" + "\n".join(str(p) for p in possible_paths)
381
+
382
+ except Exception as e:
383
+ logger.error(f"Error loading documentation: {e}", exc_info=True)
384
+ readme_content = f"Error loading documentation: {str(e)}"
385
+
386
+ return {
387
+ 'readme_content': readme_content,
388
+ 'documentation_content': documentation_html if documentation_html else None,
389
+ 'readme_path': str(readme_path) if readme_path else 'Not found',
390
+ 'readme_exists': readme_exists,
391
+ }