File size: 4,092 Bytes
592d2ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""
Management command to set up the default Python environment.

Creates a virtual environment at data/environments/default/ and registers it
in the database as the default environment for script execution.
"""

import os
import subprocess
import sys

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from core.models import Environment


class Command(BaseCommand):
    help = "Create and register the default Python environment"

    def add_arguments(self, parser):
        parser.add_argument(
            "--force",
            action="store_true",
            help="Recreate the environment even if it already exists",
        )

    def handle(self, *args, **options):
        force = options["force"]

        # Check if default environment already exists in DB
        existing = Environment.objects.filter(is_default=True).first()
        if existing and not force:
            self.stdout.write(
                self.style.WARNING(
                    f'Default environment already exists: "{existing.name}" '
                    f"at {existing.get_full_path()}"
                )
            )
            self.stdout.write("Use --force to recreate it.")
            return

        # Define paths
        env_path = "default"
        full_path = os.path.join(settings.ENVIRONMENTS_ROOT, env_path)

        # Check if directory already exists
        if os.path.exists(full_path):
            if not force:
                self.stdout.write(
                    self.style.WARNING(
                        f"Environment directory already exists: {full_path}"
                    )
                )
                self.stdout.write("Use --force to recreate it.")
                return
            else:
                self.stdout.write(f"Removing existing environment at {full_path}...")
                import shutil

                shutil.rmtree(full_path)

        # Create the virtual environment
        self.stdout.write(f"Creating virtual environment at {full_path}...")
        try:
            subprocess.run(
                [sys.executable, "-m", "venv", full_path],
                check=True,
                capture_output=True,
                text=True,
            )
        except subprocess.CalledProcessError as e:
            raise CommandError(f"Failed to create virtual environment: {e.stderr}")

        # Get Python version from the new venv
        if os.name == "nt":
            python_path = os.path.join(full_path, "Scripts", "python.exe")
        else:
            python_path = os.path.join(full_path, "bin", "python")

        try:
            result = subprocess.run(
                [python_path, "--version"],
                check=True,
                capture_output=True,
                text=True,
            )
            python_version = result.stdout.strip().replace("Python ", "")
        except subprocess.CalledProcessError:
            python_version = "unknown"

        # Create or update the Environment record
        if existing and force:
            # Update existing record
            existing.path = env_path
            existing.python_version = python_version
            existing.save()
            self.stdout.write(
                self.style.SUCCESS(
                    f'Updated default environment "{existing.name}" '
                    f"(Python {python_version})"
                )
            )
        else:
            # Create new record
            Environment.objects.create(
                name="Default Environment",
                description="Auto-created default Python environment",
                path=env_path,
                python_version=python_version,
                is_default=True,
                is_active=True,
            )
            self.stdout.write(
                self.style.SUCCESS(
                    f"Created default environment (Python {python_version})"
                )
            )

        self.stdout.write(f"Environment path: {full_path}")
        self.stdout.write(f"Python executable: {python_path}")