djlaunch 0.3.0__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.
- djlaunch/__init__.py +5 -0
- djlaunch/__main__.py +4 -0
- djlaunch/cli.py +213 -0
- djlaunch/config.py +98 -0
- djlaunch/config_file.py +66 -0
- djlaunch/doctor.py +120 -0
- djlaunch/features.py +111 -0
- djlaunch/flavors.py +111 -0
- djlaunch/generator.py +96 -0
- djlaunch/py.typed +0 -0
- djlaunch/render.py +28 -0
- djlaunch/templates/README.md.j2 +153 -0
- djlaunch/templates/apps/core/apps.py.j2 +6 -0
- djlaunch/templates/apps/core/urls.py.j2 +10 -0
- djlaunch/templates/apps/core/views.py.j2 +24 -0
- djlaunch/templates/env.example.j2 +13 -0
- djlaunch/templates/features/docker/Dockerfile.j2 +26 -0
- djlaunch/templates/features/docker/docker-compose.yml.j2 +44 -0
- djlaunch/templates/features/docker/dockerignore.j2 +13 -0
- djlaunch/templates/features/postgresql/settings.py.j2 +14 -0
- djlaunch/templates/flavors/ninja/api.py.j2 +48 -0
- djlaunch/templates/flavors/ninja/apps.py.j2 +6 -0
- djlaunch/templates/flavors/ninja/schemas.py.j2 +10 -0
- djlaunch/templates/flavors/ninja/settings.py.j2 +10 -0
- djlaunch/templates/flavors/ninja/tests.py.j2 +50 -0
- djlaunch/templates/flavors/ninja/urls.py.j2 +9 -0
- djlaunch/templates/flavors/ninja/views.py.j2 +16 -0
- djlaunch/templates/flavors/vanilla/apps.py.j2 +6 -0
- djlaunch/templates/flavors/vanilla/serializers.py.j2 +10 -0
- djlaunch/templates/flavors/vanilla/settings.py.j2 +19 -0
- djlaunch/templates/flavors/vanilla/tests.py.j2 +44 -0
- djlaunch/templates/flavors/vanilla/urls.py.j2 +17 -0
- djlaunch/templates/flavors/vanilla/views.py.j2 +23 -0
- djlaunch/templates/gitignore.j2 +30 -0
- djlaunch/templates/manage.py.j2 +23 -0
- djlaunch/templates/project/asgi.py.j2 +9 -0
- djlaunch/templates/project/settings/base.py.j2 +114 -0
- djlaunch/templates/project/settings/development.py.j2 +6 -0
- djlaunch/templates/project/settings/production.py.j2 +23 -0
- djlaunch/templates/project/urls.py.j2 +10 -0
- djlaunch/templates/project/wsgi.py.j2 +9 -0
- djlaunch/templates/requirements/base.txt.j2 +9 -0
- djlaunch/templates/requirements/development.txt.j2 +7 -0
- djlaunch/templates/requirements/production.txt.j2 +7 -0
- djlaunch/templates/requirements.txt.j2 +1 -0
- djlaunch-0.3.0.dist-info/METADATA +311 -0
- djlaunch-0.3.0.dist-info/RECORD +50 -0
- djlaunch-0.3.0.dist-info/WHEEL +4 -0
- djlaunch-0.3.0.dist-info/entry_points.txt +2 -0
- djlaunch-0.3.0.dist-info/licenses/LICENSE +21 -0
djlaunch/__init__.py
ADDED
djlaunch/__main__.py
ADDED
djlaunch/cli.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Command-line interface for djlaunch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.prompt import Confirm, Prompt
|
|
10
|
+
|
|
11
|
+
from djlaunch import __version__
|
|
12
|
+
from djlaunch.config import DEFAULT_PROJECT_NAME, ProjectConfig, validate_project_name
|
|
13
|
+
from djlaunch.config_file import ConfigFile, load_config_file
|
|
14
|
+
from djlaunch.doctor import ERROR, WARNING, diagnose
|
|
15
|
+
from djlaunch.features import FEATURES, PRESETS, validate_features
|
|
16
|
+
from djlaunch.flavors import DEFAULT_FLAVOR, FLAVORS
|
|
17
|
+
from djlaunch.generator import generate_project
|
|
18
|
+
|
|
19
|
+
console = Console()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@click.group(context_settings={'help_option_names': ['-h', '--help']})
|
|
23
|
+
@click.version_option(version=__version__, prog_name='djlaunch')
|
|
24
|
+
def cli() -> None:
|
|
25
|
+
"""Launch production-ready Django APIs in seconds."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@cli.command()
|
|
29
|
+
@click.argument('name', required=False)
|
|
30
|
+
@click.option(
|
|
31
|
+
'--output-dir',
|
|
32
|
+
'-o',
|
|
33
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
34
|
+
default=None,
|
|
35
|
+
help='Directory to create the project in. Defaults to the current directory.',
|
|
36
|
+
)
|
|
37
|
+
@click.option(
|
|
38
|
+
'--feature',
|
|
39
|
+
'features',
|
|
40
|
+
multiple=True,
|
|
41
|
+
type=click.Choice([feature.key for feature in FEATURES], case_sensitive=False),
|
|
42
|
+
help='Enable an optional feature. Repeatable.',
|
|
43
|
+
)
|
|
44
|
+
@click.option(
|
|
45
|
+
'--flavor',
|
|
46
|
+
type=click.Choice([flavor.key for flavor in FLAVORS], case_sensitive=False),
|
|
47
|
+
default=None,
|
|
48
|
+
help=f'API framework to generate. Defaults to {DEFAULT_FLAVOR}.',
|
|
49
|
+
)
|
|
50
|
+
@click.option(
|
|
51
|
+
'--preset',
|
|
52
|
+
type=click.Choice(sorted(PRESETS)),
|
|
53
|
+
default=None,
|
|
54
|
+
help='Start from a preset: minimal or full.',
|
|
55
|
+
)
|
|
56
|
+
@click.option(
|
|
57
|
+
'--config',
|
|
58
|
+
'config_path',
|
|
59
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
60
|
+
default=None,
|
|
61
|
+
help='Load name, output directory, flavor, and features from a YAML file.',
|
|
62
|
+
)
|
|
63
|
+
@click.option(
|
|
64
|
+
'--no-input',
|
|
65
|
+
is_flag=True,
|
|
66
|
+
help='Skip prompts and use defaults.',
|
|
67
|
+
)
|
|
68
|
+
def create(
|
|
69
|
+
name: str | None,
|
|
70
|
+
output_dir: Path | None,
|
|
71
|
+
features: tuple[str, ...],
|
|
72
|
+
flavor: str | None,
|
|
73
|
+
preset: str | None,
|
|
74
|
+
config_path: Path | None,
|
|
75
|
+
no_input: bool,
|
|
76
|
+
) -> None:
|
|
77
|
+
"""Create a new Django API project called NAME."""
|
|
78
|
+
config_file = ConfigFile()
|
|
79
|
+
if config_path is not None:
|
|
80
|
+
try:
|
|
81
|
+
config_file = load_config_file(config_path)
|
|
82
|
+
except ValueError as exc:
|
|
83
|
+
raise click.ClickException(str(exc)) from exc
|
|
84
|
+
|
|
85
|
+
project_name = name or config_file.name
|
|
86
|
+
if project_name is None:
|
|
87
|
+
if no_input:
|
|
88
|
+
raise click.UsageError(
|
|
89
|
+
'NAME is required when --no-input is used without a config name.'
|
|
90
|
+
)
|
|
91
|
+
project_name = Prompt.ask('Project name', default=DEFAULT_PROJECT_NAME)
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
validate_project_name(project_name)
|
|
95
|
+
except ValueError as exc:
|
|
96
|
+
raise click.ClickException(str(exc)) from exc
|
|
97
|
+
|
|
98
|
+
project_output = output_dir or config_file.output_dir or Path('.')
|
|
99
|
+
target = project_output / project_name
|
|
100
|
+
if target.exists():
|
|
101
|
+
raise click.ClickException(f'Target directory already exists: {target}')
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
selected = _select_features(
|
|
105
|
+
features=features,
|
|
106
|
+
preset=preset,
|
|
107
|
+
config_file=config_file,
|
|
108
|
+
has_config=config_path is not None,
|
|
109
|
+
no_input=no_input,
|
|
110
|
+
)
|
|
111
|
+
config = ProjectConfig(
|
|
112
|
+
name=project_name,
|
|
113
|
+
output_dir=project_output,
|
|
114
|
+
features=selected,
|
|
115
|
+
flavor=flavor or config_file.flavor or DEFAULT_FLAVOR,
|
|
116
|
+
)
|
|
117
|
+
except ValueError as exc:
|
|
118
|
+
raise click.ClickException(str(exc)) from exc
|
|
119
|
+
|
|
120
|
+
with console.status(f'Generating {config.name}...'):
|
|
121
|
+
try:
|
|
122
|
+
target = generate_project(config)
|
|
123
|
+
except OSError as exc:
|
|
124
|
+
raise click.ClickException(str(exc)) from exc
|
|
125
|
+
|
|
126
|
+
console.print(f'[green]Created[/green] {target}')
|
|
127
|
+
console.print(f'[green]Flavor[/green]: {config.api_flavor.label}')
|
|
128
|
+
if config.enabled_features:
|
|
129
|
+
labels = ', '.join(feature.label for feature in config.enabled_features)
|
|
130
|
+
console.print(f'[green]Features[/green]: {labels}')
|
|
131
|
+
console.print('\nNext steps:')
|
|
132
|
+
console.print(f' cd {target}')
|
|
133
|
+
console.print(' python -m venv .venv')
|
|
134
|
+
console.print(' source .venv/bin/activate # Windows: .venv\\Scripts\\activate')
|
|
135
|
+
console.print(' pip install -r requirements.txt')
|
|
136
|
+
console.print(' cp .env.example .env')
|
|
137
|
+
console.print(' python manage.py migrate')
|
|
138
|
+
console.print(' python manage.py test')
|
|
139
|
+
console.print(' python manage.py runserver')
|
|
140
|
+
console.print(' curl http://localhost:8000/api/v1/status/')
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _select_features(
|
|
144
|
+
*,
|
|
145
|
+
features: tuple[str, ...],
|
|
146
|
+
preset: str | None,
|
|
147
|
+
config_file: ConfigFile,
|
|
148
|
+
has_config: bool,
|
|
149
|
+
no_input: bool,
|
|
150
|
+
) -> frozenset[str]:
|
|
151
|
+
if features or preset is not None or has_config:
|
|
152
|
+
selected: set[str] = set(features)
|
|
153
|
+
if preset is not None:
|
|
154
|
+
selected.update(PRESETS[preset])
|
|
155
|
+
selected.update(config_file.features)
|
|
156
|
+
return validate_features(selected)
|
|
157
|
+
|
|
158
|
+
if no_input:
|
|
159
|
+
return validate_features(feature.key for feature in FEATURES if feature.default)
|
|
160
|
+
|
|
161
|
+
selected = set()
|
|
162
|
+
console.print('\n[bold blue]Optional features[/bold blue]')
|
|
163
|
+
console.print('Press Enter to accept the default for each.\n')
|
|
164
|
+
for feature in FEATURES:
|
|
165
|
+
console.print(f'[bold]{feature.label}[/bold]: {feature.description}')
|
|
166
|
+
if Confirm.ask('Enable?', default=feature.default):
|
|
167
|
+
selected.add(feature.key)
|
|
168
|
+
console.print()
|
|
169
|
+
|
|
170
|
+
return validate_features(selected)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@cli.command()
|
|
174
|
+
@click.argument(
|
|
175
|
+
'path',
|
|
176
|
+
type=click.Path(exists=True, file_okay=False, path_type=Path),
|
|
177
|
+
default='.',
|
|
178
|
+
)
|
|
179
|
+
@click.option('--no-check', is_flag=True, help="Skip Django's manage.py check.")
|
|
180
|
+
def doctor(path: Path, no_check: bool) -> None:
|
|
181
|
+
"""Check PATH for common problems in a generated project."""
|
|
182
|
+
results = diagnose(path, run_django_check=not no_check)
|
|
183
|
+
styles = {
|
|
184
|
+
'ok': '[green]OK [/green]',
|
|
185
|
+
'warning': '[yellow]WARN[/yellow]',
|
|
186
|
+
'error': '[red]FAIL[/red]',
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
for result in results:
|
|
190
|
+
console.print(f'{styles[result.status]} {result.label}')
|
|
191
|
+
if result.detail:
|
|
192
|
+
for line in result.detail.splitlines():
|
|
193
|
+
console.print(f' {line}')
|
|
194
|
+
|
|
195
|
+
problems = [result for result in results if result.status == ERROR]
|
|
196
|
+
warnings = [result for result in results if result.status == WARNING]
|
|
197
|
+
console.print()
|
|
198
|
+
if problems:
|
|
199
|
+
console.print(
|
|
200
|
+
f'[red]{len(problems)} problem(s) found[/red]'
|
|
201
|
+
+ (f', {len(warnings)} warning(s).' if warnings else '.')
|
|
202
|
+
)
|
|
203
|
+
raise click.exceptions.Exit(1)
|
|
204
|
+
|
|
205
|
+
if warnings:
|
|
206
|
+
console.print(f'[yellow]{len(warnings)} warning(s)[/yellow], no problems found.')
|
|
207
|
+
else:
|
|
208
|
+
console.print('[green]Project looks healthy.[/green]')
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def main() -> None:
|
|
212
|
+
"""Entry point for the ``djlaunch`` console script."""
|
|
213
|
+
cli()
|
djlaunch/config.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Validated configuration for a generated project."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import keyword
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from djlaunch.features import FEATURES, EnvVar, Feature, RequirementGroup, validate_features
|
|
11
|
+
from djlaunch.flavors import DEFAULT_FLAVOR, FLAVOR_BY_KEY, Flavor, validate_flavor
|
|
12
|
+
|
|
13
|
+
DEFAULT_PROJECT_NAME = 'my_project'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class ProjectConfig:
|
|
18
|
+
"""Everything the generator needs to render a project."""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
output_dir: Path = field(default_factory=Path)
|
|
22
|
+
features: frozenset[str] = field(default_factory=frozenset)
|
|
23
|
+
flavor: str = DEFAULT_FLAVOR
|
|
24
|
+
|
|
25
|
+
def __post_init__(self) -> None:
|
|
26
|
+
validate_project_name(self.name)
|
|
27
|
+
object.__setattr__(self, 'output_dir', Path(self.output_dir).expanduser())
|
|
28
|
+
object.__setattr__(self, 'features', validate_features(self.features))
|
|
29
|
+
object.__setattr__(self, 'flavor', validate_flavor(self.flavor))
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def target_dir(self) -> Path:
|
|
33
|
+
"""Directory that will contain the generated project."""
|
|
34
|
+
return self.output_dir / self.name
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def title(self) -> str:
|
|
38
|
+
"""Human-readable project name."""
|
|
39
|
+
return self.name.replace('_', ' ').replace('-', ' ').title()
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def api_flavor(self) -> Flavor:
|
|
43
|
+
"""The selected API flavor."""
|
|
44
|
+
return FLAVOR_BY_KEY[self.flavor]
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def server_command(self) -> tuple[str, ...]:
|
|
48
|
+
"""Production server command for the selected flavor."""
|
|
49
|
+
return tuple(part.format(project=self.name) for part in self.api_flavor.server_command)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def enabled_features(self) -> tuple[Feature, ...]:
|
|
53
|
+
"""Selected features in registry order."""
|
|
54
|
+
return tuple(feature for feature in FEATURES if feature.key in self.features)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def feature_requirements(self) -> dict[str, tuple[str, ...]]:
|
|
58
|
+
"""Packages contributed by features, grouped by requirements file."""
|
|
59
|
+
return _group_requirements(
|
|
60
|
+
group for feature in self.enabled_features for group in feature.requirements
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def flavor_requirements(self) -> dict[str, tuple[str, ...]]:
|
|
65
|
+
"""Packages contributed by the flavor, grouped by requirements file."""
|
|
66
|
+
return _group_requirements(self.api_flavor.requirements)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def feature_env(self) -> tuple[EnvVar, ...]:
|
|
70
|
+
"""Environment variables contributed by enabled features."""
|
|
71
|
+
return tuple(var for feature in self.enabled_features for var in feature.env)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def flavor_env(self) -> tuple[EnvVar, ...]:
|
|
75
|
+
"""Environment variables contributed by the flavor."""
|
|
76
|
+
return self.api_flavor.env
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def feature_settings(self) -> tuple[Feature, ...]:
|
|
80
|
+
"""Enabled features that contribute a settings module."""
|
|
81
|
+
return tuple(feature for feature in self.enabled_features if feature.settings_fragment)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _group_requirements(groups: Iterable[RequirementGroup]) -> dict[str, tuple[str, ...]]:
|
|
85
|
+
grouped: dict[str, list[str]] = {'base': [], 'development': [], 'production': []}
|
|
86
|
+
for group in groups:
|
|
87
|
+
grouped.setdefault(group.file, []).extend(group.packages)
|
|
88
|
+
return {name: tuple(packages) for name, packages in grouped.items()}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def validate_project_name(name: str) -> None:
|
|
92
|
+
if not name:
|
|
93
|
+
raise ValueError('Project name cannot be empty.')
|
|
94
|
+
if not name.isidentifier() or keyword.iskeyword(name):
|
|
95
|
+
raise ValueError(
|
|
96
|
+
'Project name must be a valid Python identifier '
|
|
97
|
+
'(letters, numbers, and underscores; cannot start with a number).'
|
|
98
|
+
)
|
djlaunch/config_file.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Load project settings from a YAML file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
CONFIG_KEYS = frozenset({'name', 'output_dir', 'flavor', 'features'})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class ConfigFile:
|
|
16
|
+
"""Values read from a ``project.yml`` file."""
|
|
17
|
+
|
|
18
|
+
name: str | None = None
|
|
19
|
+
output_dir: Path | None = None
|
|
20
|
+
flavor: str | None = None
|
|
21
|
+
features: tuple[str, ...] = ()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load_config_file(path: Path) -> ConfigFile:
|
|
25
|
+
"""Read and validate a project config file."""
|
|
26
|
+
try:
|
|
27
|
+
raw: Any = yaml.safe_load(path.read_text(encoding='utf-8'))
|
|
28
|
+
except OSError as exc:
|
|
29
|
+
raise ValueError(f'Could not read {path}: {exc}') from exc
|
|
30
|
+
except yaml.YAMLError as exc:
|
|
31
|
+
raise ValueError(f'Invalid YAML in {path}: {exc}') from exc
|
|
32
|
+
|
|
33
|
+
if raw is None:
|
|
34
|
+
return ConfigFile()
|
|
35
|
+
|
|
36
|
+
if not isinstance(raw, dict):
|
|
37
|
+
raise ValueError(f'{path} must contain a mapping.')
|
|
38
|
+
|
|
39
|
+
unknown = set(raw) - CONFIG_KEYS
|
|
40
|
+
if unknown:
|
|
41
|
+
raise ValueError(f'Unknown config keys: {", ".join(sorted(unknown))}.')
|
|
42
|
+
|
|
43
|
+
name = raw.get('name')
|
|
44
|
+
if name is not None and not isinstance(name, str):
|
|
45
|
+
raise ValueError('config "name" must be a string.')
|
|
46
|
+
|
|
47
|
+
output_dir = raw.get('output_dir')
|
|
48
|
+
if output_dir is not None:
|
|
49
|
+
if not isinstance(output_dir, str):
|
|
50
|
+
raise ValueError('config "output_dir" must be a string.')
|
|
51
|
+
output_dir = Path(output_dir)
|
|
52
|
+
|
|
53
|
+
flavor = raw.get('flavor')
|
|
54
|
+
if flavor is not None and not isinstance(flavor, str):
|
|
55
|
+
raise ValueError('config "flavor" must be a string.')
|
|
56
|
+
|
|
57
|
+
features = raw.get('features', [])
|
|
58
|
+
if not isinstance(features, list) or not all(isinstance(item, str) for item in features):
|
|
59
|
+
raise ValueError('config "features" must be a list of feature names.')
|
|
60
|
+
|
|
61
|
+
return ConfigFile(
|
|
62
|
+
name=name,
|
|
63
|
+
output_dir=output_dir,
|
|
64
|
+
flavor=flavor,
|
|
65
|
+
features=tuple(features),
|
|
66
|
+
)
|
djlaunch/doctor.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Structural and runtime checks for a generated project."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
OK = 'ok'
|
|
11
|
+
WARNING = 'warning'
|
|
12
|
+
ERROR = 'error'
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class Diagnostic:
|
|
17
|
+
"""One result from a project check."""
|
|
18
|
+
|
|
19
|
+
status: str
|
|
20
|
+
label: str
|
|
21
|
+
detail: str = ''
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def diagnose(path: Path, *, run_django_check: bool = True) -> list[Diagnostic]:
|
|
25
|
+
"""Check a generated project and return every diagnostic."""
|
|
26
|
+
results: list[Diagnostic] = []
|
|
27
|
+
path = path.resolve()
|
|
28
|
+
|
|
29
|
+
if not (path / 'manage.py').is_file():
|
|
30
|
+
results.append(Diagnostic(ERROR, 'manage.py', 'Missing manage.py; is this a project root?'))
|
|
31
|
+
return results
|
|
32
|
+
|
|
33
|
+
results.append(Diagnostic(OK, 'manage.py'))
|
|
34
|
+
|
|
35
|
+
settings_packages = sorted(
|
|
36
|
+
candidate.parent.parent.name
|
|
37
|
+
for candidate in path.glob('*/settings/base.py')
|
|
38
|
+
if candidate.is_file()
|
|
39
|
+
)
|
|
40
|
+
if len(settings_packages) == 1:
|
|
41
|
+
results.append(Diagnostic(OK, 'settings package', settings_packages[0]))
|
|
42
|
+
elif not settings_packages:
|
|
43
|
+
results.append(Diagnostic(ERROR, 'settings package', 'No */settings/base.py found.'))
|
|
44
|
+
else:
|
|
45
|
+
found = ', '.join(settings_packages)
|
|
46
|
+
results.append(Diagnostic(ERROR, 'settings package', f'Multiple candidates: {found}.'))
|
|
47
|
+
|
|
48
|
+
for name in ('development.py', 'production.py'):
|
|
49
|
+
target = path / settings_packages[0] / 'settings' / name if settings_packages else None
|
|
50
|
+
if target is not None and target.is_file():
|
|
51
|
+
results.append(Diagnostic(OK, f'settings/{name}'))
|
|
52
|
+
else:
|
|
53
|
+
results.append(Diagnostic(ERROR, f'settings/{name}', 'Missing split settings module.'))
|
|
54
|
+
|
|
55
|
+
requirements = path / 'requirements' / 'base.txt'
|
|
56
|
+
if requirements.is_file():
|
|
57
|
+
results.append(Diagnostic(OK, 'requirements/base.txt'))
|
|
58
|
+
else:
|
|
59
|
+
results.append(Diagnostic(ERROR, 'requirements/base.txt', 'Missing base requirements.'))
|
|
60
|
+
|
|
61
|
+
if (path / '.env').is_file():
|
|
62
|
+
results.append(Diagnostic(OK, '.env'))
|
|
63
|
+
elif (path / '.env.example').is_file():
|
|
64
|
+
results.append(
|
|
65
|
+
Diagnostic(WARNING, '.env', 'Only .env.example exists; copy it to .env before running.')
|
|
66
|
+
)
|
|
67
|
+
else:
|
|
68
|
+
results.append(Diagnostic(ERROR, '.env', 'Neither .env nor .env.example exists.'))
|
|
69
|
+
|
|
70
|
+
if (path / 'apps' / 'core' / 'views.py').is_file():
|
|
71
|
+
results.append(Diagnostic(OK, 'apps/core'))
|
|
72
|
+
else:
|
|
73
|
+
results.append(Diagnostic(WARNING, 'apps/core', 'Core API app is missing.'))
|
|
74
|
+
|
|
75
|
+
if (path / 'apps' / 'api' / 'urls.py').is_file():
|
|
76
|
+
results.append(Diagnostic(OK, 'apps/api'))
|
|
77
|
+
else:
|
|
78
|
+
results.append(
|
|
79
|
+
Diagnostic(WARNING, 'apps/api', 'API app is missing; /api/v1/ is not mounted.')
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
docker_markers = [
|
|
83
|
+
name for name in ('Dockerfile', 'docker-compose.yml') if (path / name).is_file()
|
|
84
|
+
]
|
|
85
|
+
if docker_markers and len(docker_markers) == 1:
|
|
86
|
+
missing = 'docker-compose.yml' if docker_markers[0] == 'Dockerfile' else 'Dockerfile'
|
|
87
|
+
results.append(
|
|
88
|
+
Diagnostic(ERROR, 'Docker', f'{docker_markers[0]} exists but {missing} is missing.')
|
|
89
|
+
)
|
|
90
|
+
elif docker_markers:
|
|
91
|
+
results.append(Diagnostic(OK, 'Docker'))
|
|
92
|
+
|
|
93
|
+
if run_django_check:
|
|
94
|
+
results.append(_django_check(path))
|
|
95
|
+
|
|
96
|
+
return results
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _django_check(path: Path) -> Diagnostic:
|
|
100
|
+
try:
|
|
101
|
+
completed = subprocess.run(
|
|
102
|
+
[sys.executable, 'manage.py', 'check'],
|
|
103
|
+
cwd=path,
|
|
104
|
+
capture_output=True,
|
|
105
|
+
text=True,
|
|
106
|
+
timeout=60,
|
|
107
|
+
check=False,
|
|
108
|
+
)
|
|
109
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
110
|
+
return Diagnostic(ERROR, 'manage.py check', str(exc))
|
|
111
|
+
|
|
112
|
+
if completed.returncode == 0:
|
|
113
|
+
return Diagnostic(OK, 'manage.py check')
|
|
114
|
+
|
|
115
|
+
output = (completed.stderr or completed.stdout).strip()
|
|
116
|
+
return Diagnostic(
|
|
117
|
+
ERROR,
|
|
118
|
+
'manage.py check',
|
|
119
|
+
output or f'Exited with status {completed.returncode}.',
|
|
120
|
+
)
|
djlaunch/features.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Optional project features and the files they contribute."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class TemplateFile:
|
|
11
|
+
"""A template and the path it renders to inside the generated project."""
|
|
12
|
+
|
|
13
|
+
template: str
|
|
14
|
+
destination: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class EnvVar:
|
|
19
|
+
"""An environment variable contributed by a feature."""
|
|
20
|
+
|
|
21
|
+
key: str
|
|
22
|
+
default: str
|
|
23
|
+
comment: str = ''
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class RequirementGroup:
|
|
28
|
+
"""Packages added to one generated requirements file."""
|
|
29
|
+
|
|
30
|
+
file: str
|
|
31
|
+
packages: tuple[str, ...]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class Feature:
|
|
36
|
+
"""One optional capability and everything it contributes."""
|
|
37
|
+
|
|
38
|
+
key: str
|
|
39
|
+
label: str
|
|
40
|
+
description: str
|
|
41
|
+
default: bool = False
|
|
42
|
+
requires: tuple[str, ...] = ()
|
|
43
|
+
conflicts: tuple[str, ...] = ()
|
|
44
|
+
templates: tuple[TemplateFile, ...] = ()
|
|
45
|
+
requirements: tuple[RequirementGroup, ...] = ()
|
|
46
|
+
env: tuple[EnvVar, ...] = ()
|
|
47
|
+
settings_fragment: str | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
FEATURES: tuple[Feature, ...] = (
|
|
51
|
+
Feature(
|
|
52
|
+
key='docker',
|
|
53
|
+
label='Docker',
|
|
54
|
+
description='Production Docker image, Compose stack, and .dockerignore. On by default.',
|
|
55
|
+
default=True,
|
|
56
|
+
templates=(
|
|
57
|
+
TemplateFile('features/docker/Dockerfile.j2', 'Dockerfile'),
|
|
58
|
+
TemplateFile('features/docker/docker-compose.yml.j2', 'docker-compose.yml'),
|
|
59
|
+
TemplateFile('features/docker/dockerignore.j2', '.dockerignore'),
|
|
60
|
+
),
|
|
61
|
+
),
|
|
62
|
+
Feature(
|
|
63
|
+
key='postgresql',
|
|
64
|
+
label='PostgreSQL',
|
|
65
|
+
description='PostgreSQL database settings and psycopg. On by default.',
|
|
66
|
+
default=True,
|
|
67
|
+
requirements=(RequirementGroup('base', ('psycopg[binary]>=3.2',)),),
|
|
68
|
+
env=(
|
|
69
|
+
EnvVar('POSTGRES_DB', 'postgres', 'PostgreSQL database name'),
|
|
70
|
+
EnvVar('POSTGRES_USER', 'postgres', 'PostgreSQL user'),
|
|
71
|
+
EnvVar('POSTGRES_PASSWORD', 'postgres', 'PostgreSQL password'),
|
|
72
|
+
EnvVar('POSTGRES_HOST', 'localhost', "PostgreSQL host ('db' inside Compose)"),
|
|
73
|
+
EnvVar('POSTGRES_PORT', '5432', 'PostgreSQL port'),
|
|
74
|
+
),
|
|
75
|
+
settings_fragment='features/postgresql/settings.py.j2',
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
FEATURE_BY_KEY: Mapping[str, Feature] = {feature.key: feature for feature in FEATURES}
|
|
80
|
+
|
|
81
|
+
PRESETS: Mapping[str, tuple[str, ...]] = {
|
|
82
|
+
'minimal': (),
|
|
83
|
+
'full': tuple(feature.key for feature in FEATURES),
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def validate_features(
|
|
88
|
+
selected: Iterable[str],
|
|
89
|
+
registry: Mapping[str, Feature] | None = None,
|
|
90
|
+
) -> frozenset[str]:
|
|
91
|
+
"""Validate feature selection and return it as a frozenset."""
|
|
92
|
+
registry = registry if registry is not None else FEATURE_BY_KEY
|
|
93
|
+
selected_set = frozenset(selected)
|
|
94
|
+
|
|
95
|
+
unknown = selected_set - registry.keys()
|
|
96
|
+
if unknown:
|
|
97
|
+
available = ', '.join(sorted(registry))
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f'Unknown feature(s): {", ".join(sorted(unknown))}. Available: {available}.'
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
for key in sorted(selected_set):
|
|
103
|
+
feature = registry[key]
|
|
104
|
+
missing = set(feature.requires) - selected_set
|
|
105
|
+
if missing:
|
|
106
|
+
raise ValueError(f"Feature '{key}' requires: {', '.join(sorted(missing))}.")
|
|
107
|
+
conflicts = set(feature.conflicts) & selected_set
|
|
108
|
+
if conflicts:
|
|
109
|
+
raise ValueError(f"Feature '{key}' conflicts with: {', '.join(sorted(conflicts))}.")
|
|
110
|
+
|
|
111
|
+
return selected_set
|