Skip to content

Commit

Permalink
Merge pull request #28 from fourdigits/21-auto-detect-settings-module
Browse files Browse the repository at this point in the history
Add auto detect for django settings module
  • Loading branch information
rubenhesselink authored Jun 19, 2024
2 parents b401044 + 80fd393 commit 12bc3ae
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions djlsp/scripts/django-collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import re
import sys
from unittest.mock import patch

import django
from django.apps import apps
Expand Down Expand Up @@ -390,6 +391,22 @@ def collect_project_data():
}


def get_default_django_settings_module():
try:
# Patch django execute to prevent it from running when calling main
with patch(
"django.core.management.execute_from_command_line", return_value=None
):
from manage import main

# Need to run main becuase default env is set in main function
main()

return os.getenv("DJANGO_SETTINGS_MODULE")
except ImportError:
return ""


if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="""
Expand All @@ -401,18 +418,22 @@ def collect_project_data():
parser.add_argument("--project-src", action="store", type=str)
args = parser.parse_args()

if args.django_settings_module:
# TODO: Auto detect when empty?
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
args.django_settings_module,
)

if args.project_src:
sys.path.insert(0, args.project_src)
else:
sys.path.insert(0, os.getcwd())

django_settings_module = (
args.django_settings_module
if args.django_settings_module
else get_default_django_settings_module()
)
if args.django_settings_module:
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
django_settings_module,
)

django.setup()

print(json.dumps(collect_project_data(), indent=4))

0 comments on commit 12bc3ae

Please sign in to comment.