django-routines 1.0.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Brian Kohan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,225 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-routines
3
+ Version: 1.0.0
4
+ Summary: Configure named groups of management commands in Django settings files.
5
+ Home-page: https://django-routines.readthedocs.io
6
+ License: MIT
7
+ Keywords: django,CLI,management,routine,routines,batch,commands,deploy
8
+ Author: Brian Kohan
9
+ Author-email: bckohan@gmail.com
10
+ Requires-Python: >=3.8,<4.0
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 3.2
15
+ Classifier: Framework :: Django :: 4.0
16
+ Classifier: Framework :: Django :: 4.1
17
+ Classifier: Framework :: Django :: 4.2
18
+ Classifier: Framework :: Django :: 5.0
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Classifier: Natural Language :: English
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Programming Language :: Python
24
+ Classifier: Programming Language :: Python :: 3
25
+ Classifier: Programming Language :: Python :: 3.8
26
+ Classifier: Programming Language :: Python :: 3.9
27
+ Classifier: Programming Language :: Python :: 3.10
28
+ Classifier: Programming Language :: Python :: 3.11
29
+ Classifier: Programming Language :: Python :: 3.12
30
+ Classifier: Topic :: Internet :: WWW/HTTP
31
+ Classifier: Topic :: Internet :: WWW/HTTP :: Site Management
32
+ Classifier: Topic :: Software Development :: Libraries
33
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
34
+ Provides-Extra: rich
35
+ Requires-Dist: Django (>=3.2,<6.0)
36
+ Requires-Dist: django-typer (>=2.0.2,<3.0.0)
37
+ Requires-Dist: rich (>=10.11.0,<14.0.0) ; extra == "rich"
38
+ Requires-Dist: typing-extensions (>=3.7.4.3) ; python_version < "3.10"
39
+ Project-URL: Repository, https://github.com/bckohan/django-routines
40
+ Description-Content-Type: text/markdown
41
+
42
+ # django-routines
43
+
44
+
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
46
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
47
+ [![PyPI version](https://badge.fury.io/py/django-routines.svg)](https://pypi.python.org/pypi/django-routines/)
48
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/django-routines.svg)](https://pypi.python.org/pypi/django-routines/)
49
+ [![PyPI djversions](https://img.shields.io/pypi/djversions/django-routines.svg)](https://pypi.org/project/django-routines/)
50
+ [![PyPI status](https://img.shields.io/pypi/status/django-routines.svg)](https://pypi.python.org/pypi/django-routines)
51
+ [![Documentation Status](https://readthedocs.org/projects/django-routines/badge/?version=latest)](http://django-routines.readthedocs.io/?badge=latest/)
52
+ [![Code Cov](https://codecov.io/gh/bckohan/django-routines/branch/main/graph/badge.svg?token=0IZOKN2DYL)](https://codecov.io/gh/bckohan/django-routines)
53
+ [![Test Status](https://github.com/bckohan/django-routines/workflows/test/badge.svg)](https://github.com/bckohan/django-routines/actions/workflows/test.yml)
54
+ [![Lint Status](https://github.com/bckohan/django-routines/workflows/lint/badge.svg)](https://github.com/bckohan/django-routines/actions/workflows/lint.yml)
55
+
56
+
57
+ Configure batches of Django management commands in your settings files and run them all at once.
58
+ For example, batch together your common database maintenance tasks, deployment routines or any
59
+ other set of commands you need to run together. This helps single source general site maintenance
60
+ into your settings files keeping your code base [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
61
+
62
+ ## Example
63
+
64
+ Let's define two named routines, "package" and "deploy". The package routine will be a collection
65
+ of commands that we typically run to generate package artifacts (like migrations and transpiled
66
+ javascript). The deploy routine will be a collection of commands we typically run when deploying
67
+ the site for the first time on a new server or when we deploy version updates on the server.
68
+
69
+ **Routines commands are run in the order they are registered, or by [priority](#priorities).**
70
+
71
+ ```python
72
+ from django_routines import RoutineCommand, command, routine
73
+
74
+ # register routines and their help text
75
+ routine(
76
+ name="package",
77
+ help_text=(
78
+ "Generate pre-package artifacts like migrations and transpiled "
79
+ "javascript."
80
+ )
81
+ )
82
+ # you may register commands on a routine after defining a routine (or before!)
83
+ command("package", "makemigrations")
84
+ command("package", "renderstatic")
85
+
86
+ routine(
87
+ "deploy",
88
+ "Deploy the site application into production.",
89
+
90
+ # you may also specify commands inline using the RoutineCommand dataclass
91
+ RoutineCommand(
92
+ ("routine", "package"), switches=["prepare"]
93
+ ), # routine commands can be other routines!
94
+ RoutineCommand("migrate"),
95
+ RoutineCommand("collectstatic"),
96
+ RoutineCommand(("shellcompletion", "install"), switches=["initial"]),
97
+ RoutineCommand(("loaddata", "./fixtures/demo.json"), switches=["demo"]),
98
+
99
+ # define switches that toggle commands on and off
100
+ prepare="Generate artifacts like migrations and transpiled javascript.",
101
+ initial="Things to do on the very first deployment on a new server.",
102
+ demo="Load the demo data.",
103
+ )
104
+ ```
105
+
106
+ The routine command will read our settings file and generate two subcommands, one called deploy and one called package:
107
+
108
+ ![package](https://raw.githubusercontent.com/bckohan/django-routines/main/examples/package.svg)
109
+
110
+ Now we can run all of our package routines with one command:
111
+
112
+ ```bash
113
+ ?> ./manage.py routine package
114
+ makemigrations
115
+ ...
116
+ renderstatic
117
+ ...
118
+ ```
119
+
120
+ The deploy command has several switches that we can enable to run additional commands.
121
+
122
+ ![deploy](https://raw.githubusercontent.com/bckohan/django-routines/main/examples/deploy.svg)
123
+
124
+ For example to deploy our demo on a new server we would run:
125
+
126
+ ```bash
127
+ ?> ./manage.py routine deploy --initial --demo
128
+ migrate
129
+ ...
130
+ collectstatic
131
+ ...
132
+ shellcompletion install
133
+ ...
134
+ loaddata ./fixtures/demo.json
135
+ ...
136
+ ```
137
+
138
+ ## Settings
139
+
140
+ The [RoutineCommand](https://django-routines.readthedocs.io/en/latest/reference.html#django_routines.RoutineCommand) dataclass, [routine](https://django-routines.readthedocs.io/en/latest/reference.html#django_routines.routine) and [command](https://django-routines.readthedocs.io/en/latest/reference.html#django_routines.command) helper functions in the example above make it easier for us to work with the native configuration format which is a dictionary structure defined in the ``DJANGO_ROUTINES`` setting attribute. For example the above configuration is equivalent to:
141
+
142
+ ```python
143
+ DJANGO_ROUTINES = {
144
+ "deploy": {
145
+ "commands": [
146
+ {"command": ("routine", "package"), "switches": ["prepare"]},
147
+ {"command": "migrate"},
148
+ {"command": "collectstatic"},
149
+ {
150
+ "command": ("shellcompletion", "install"),
151
+ "switches": ["initial"],
152
+ },
153
+ {
154
+ "command": ("loaddata", "./fixtures/demo.json"),
155
+ "switches": ["demo"],
156
+ },
157
+ ],
158
+ "help_text": "Deploy the site application into production.",
159
+ "name": "deploy",
160
+ "switch_helps": {
161
+ "demo": "Load the demo data.",
162
+ "initial": "Things to do on the very first deployment on a new server.",
163
+ "prepare": "Generate artifacts like migrations and transpiled javascript.",
164
+ },
165
+ },
166
+ "package": {
167
+ "commands": [
168
+ {"command": "makemigrations"},
169
+ {"command": "renderstatic"},
170
+ ],
171
+ "help_text": "Generate pre-package artifacts like migrations and transpiled javascript.",
172
+ "name": "package",
173
+ },
174
+ }
175
+ ```
176
+
177
+
178
+ ## Priorities
179
+
180
+ If you are composing settings from multiple apps or source files using a utility like [django-split-settings](https://pypi.org/project/django-split-settings/) you may not be able to define all routines at once. You can use priorities to make sure commands defined in a de-coupled way run in the correct order.
181
+
182
+ ```python
183
+ command("deploy", "makemigrations", priority=1)
184
+ command("deploy", "migrate", priority=2)
185
+ ```
186
+
187
+ ## Options
188
+
189
+ When specifying arguments you may add them to the command tuple OR specify them as named options in the style that will be passed to [call_command](https://docs.djangoproject.com/en/stable/ref/django-admin/#django.core.management.call_command):
190
+
191
+ ```python
192
+ # these two are equivalent
193
+ command("package", ("makemigrations", "--no-header"))
194
+ command("package", "makemigrations", no_header=True)
195
+ ```
196
+
197
+
198
+ ## Installation
199
+
200
+
201
+ 1. Clone django-routines from [GitHub](https://github.com/bckohan/django-routines) or install a release off [PyPI](https://pypi.python.org/pypi/django-routines) :
202
+
203
+ ```bash
204
+ pip install django-routines
205
+ ```
206
+
207
+ [rich](https://rich.readthedocs.io/) is a powerful library for rich text and beautiful formatting in the terminal. It is not required, but highly recommended for the best experience:
208
+
209
+ ```bash
210
+ pip install "django-routines[rich]"
211
+ ```
212
+
213
+
214
+ 2. Add ``django_routines`` to your ``INSTALLED_APPS`` setting:
215
+
216
+ ```python
217
+ INSTALLED_APPS = [
218
+ ...
219
+ 'django_routines',
220
+ 'django_typer', # optional!
221
+ ]
222
+ ```
223
+
224
+ *You only need to install django_typer as an app if you want to use the shellcompletion command to [enable tab-completion](https://django-typer.readthedocs.io/en/latest/shell_completion.html) or if you would like django-typer to install [rich traceback rendering](https://django-typer.readthedocs.io/en/latest/howto.html#configure-rich-stack-traces) for you - which it does by default if rich is also installed.*
225
+
@@ -0,0 +1,183 @@
1
+ # django-routines
2
+
3
+
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
6
+ [![PyPI version](https://badge.fury.io/py/django-routines.svg)](https://pypi.python.org/pypi/django-routines/)
7
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/django-routines.svg)](https://pypi.python.org/pypi/django-routines/)
8
+ [![PyPI djversions](https://img.shields.io/pypi/djversions/django-routines.svg)](https://pypi.org/project/django-routines/)
9
+ [![PyPI status](https://img.shields.io/pypi/status/django-routines.svg)](https://pypi.python.org/pypi/django-routines)
10
+ [![Documentation Status](https://readthedocs.org/projects/django-routines/badge/?version=latest)](http://django-routines.readthedocs.io/?badge=latest/)
11
+ [![Code Cov](https://codecov.io/gh/bckohan/django-routines/branch/main/graph/badge.svg?token=0IZOKN2DYL)](https://codecov.io/gh/bckohan/django-routines)
12
+ [![Test Status](https://github.com/bckohan/django-routines/workflows/test/badge.svg)](https://github.com/bckohan/django-routines/actions/workflows/test.yml)
13
+ [![Lint Status](https://github.com/bckohan/django-routines/workflows/lint/badge.svg)](https://github.com/bckohan/django-routines/actions/workflows/lint.yml)
14
+
15
+
16
+ Configure batches of Django management commands in your settings files and run them all at once.
17
+ For example, batch together your common database maintenance tasks, deployment routines or any
18
+ other set of commands you need to run together. This helps single source general site maintenance
19
+ into your settings files keeping your code base [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
20
+
21
+ ## Example
22
+
23
+ Let's define two named routines, "package" and "deploy". The package routine will be a collection
24
+ of commands that we typically run to generate package artifacts (like migrations and transpiled
25
+ javascript). The deploy routine will be a collection of commands we typically run when deploying
26
+ the site for the first time on a new server or when we deploy version updates on the server.
27
+
28
+ **Routines commands are run in the order they are registered, or by [priority](#priorities).**
29
+
30
+ ```python
31
+ from django_routines import RoutineCommand, command, routine
32
+
33
+ # register routines and their help text
34
+ routine(
35
+ name="package",
36
+ help_text=(
37
+ "Generate pre-package artifacts like migrations and transpiled "
38
+ "javascript."
39
+ )
40
+ )
41
+ # you may register commands on a routine after defining a routine (or before!)
42
+ command("package", "makemigrations")
43
+ command("package", "renderstatic")
44
+
45
+ routine(
46
+ "deploy",
47
+ "Deploy the site application into production.",
48
+
49
+ # you may also specify commands inline using the RoutineCommand dataclass
50
+ RoutineCommand(
51
+ ("routine", "package"), switches=["prepare"]
52
+ ), # routine commands can be other routines!
53
+ RoutineCommand("migrate"),
54
+ RoutineCommand("collectstatic"),
55
+ RoutineCommand(("shellcompletion", "install"), switches=["initial"]),
56
+ RoutineCommand(("loaddata", "./fixtures/demo.json"), switches=["demo"]),
57
+
58
+ # define switches that toggle commands on and off
59
+ prepare="Generate artifacts like migrations and transpiled javascript.",
60
+ initial="Things to do on the very first deployment on a new server.",
61
+ demo="Load the demo data.",
62
+ )
63
+ ```
64
+
65
+ The routine command will read our settings file and generate two subcommands, one called deploy and one called package:
66
+
67
+ ![package](https://raw.githubusercontent.com/bckohan/django-routines/main/examples/package.svg)
68
+
69
+ Now we can run all of our package routines with one command:
70
+
71
+ ```bash
72
+ ?> ./manage.py routine package
73
+ makemigrations
74
+ ...
75
+ renderstatic
76
+ ...
77
+ ```
78
+
79
+ The deploy command has several switches that we can enable to run additional commands.
80
+
81
+ ![deploy](https://raw.githubusercontent.com/bckohan/django-routines/main/examples/deploy.svg)
82
+
83
+ For example to deploy our demo on a new server we would run:
84
+
85
+ ```bash
86
+ ?> ./manage.py routine deploy --initial --demo
87
+ migrate
88
+ ...
89
+ collectstatic
90
+ ...
91
+ shellcompletion install
92
+ ...
93
+ loaddata ./fixtures/demo.json
94
+ ...
95
+ ```
96
+
97
+ ## Settings
98
+
99
+ The [RoutineCommand](https://django-routines.readthedocs.io/en/latest/reference.html#django_routines.RoutineCommand) dataclass, [routine](https://django-routines.readthedocs.io/en/latest/reference.html#django_routines.routine) and [command](https://django-routines.readthedocs.io/en/latest/reference.html#django_routines.command) helper functions in the example above make it easier for us to work with the native configuration format which is a dictionary structure defined in the ``DJANGO_ROUTINES`` setting attribute. For example the above configuration is equivalent to:
100
+
101
+ ```python
102
+ DJANGO_ROUTINES = {
103
+ "deploy": {
104
+ "commands": [
105
+ {"command": ("routine", "package"), "switches": ["prepare"]},
106
+ {"command": "migrate"},
107
+ {"command": "collectstatic"},
108
+ {
109
+ "command": ("shellcompletion", "install"),
110
+ "switches": ["initial"],
111
+ },
112
+ {
113
+ "command": ("loaddata", "./fixtures/demo.json"),
114
+ "switches": ["demo"],
115
+ },
116
+ ],
117
+ "help_text": "Deploy the site application into production.",
118
+ "name": "deploy",
119
+ "switch_helps": {
120
+ "demo": "Load the demo data.",
121
+ "initial": "Things to do on the very first deployment on a new server.",
122
+ "prepare": "Generate artifacts like migrations and transpiled javascript.",
123
+ },
124
+ },
125
+ "package": {
126
+ "commands": [
127
+ {"command": "makemigrations"},
128
+ {"command": "renderstatic"},
129
+ ],
130
+ "help_text": "Generate pre-package artifacts like migrations and transpiled javascript.",
131
+ "name": "package",
132
+ },
133
+ }
134
+ ```
135
+
136
+
137
+ ## Priorities
138
+
139
+ If you are composing settings from multiple apps or source files using a utility like [django-split-settings](https://pypi.org/project/django-split-settings/) you may not be able to define all routines at once. You can use priorities to make sure commands defined in a de-coupled way run in the correct order.
140
+
141
+ ```python
142
+ command("deploy", "makemigrations", priority=1)
143
+ command("deploy", "migrate", priority=2)
144
+ ```
145
+
146
+ ## Options
147
+
148
+ When specifying arguments you may add them to the command tuple OR specify them as named options in the style that will be passed to [call_command](https://docs.djangoproject.com/en/stable/ref/django-admin/#django.core.management.call_command):
149
+
150
+ ```python
151
+ # these two are equivalent
152
+ command("package", ("makemigrations", "--no-header"))
153
+ command("package", "makemigrations", no_header=True)
154
+ ```
155
+
156
+
157
+ ## Installation
158
+
159
+
160
+ 1. Clone django-routines from [GitHub](https://github.com/bckohan/django-routines) or install a release off [PyPI](https://pypi.python.org/pypi/django-routines) :
161
+
162
+ ```bash
163
+ pip install django-routines
164
+ ```
165
+
166
+ [rich](https://rich.readthedocs.io/) is a powerful library for rich text and beautiful formatting in the terminal. It is not required, but highly recommended for the best experience:
167
+
168
+ ```bash
169
+ pip install "django-routines[rich]"
170
+ ```
171
+
172
+
173
+ 2. Add ``django_routines`` to your ``INSTALLED_APPS`` setting:
174
+
175
+ ```python
176
+ INSTALLED_APPS = [
177
+ ...
178
+ 'django_routines',
179
+ 'django_typer', # optional!
180
+ ]
181
+ ```
182
+
183
+ *You only need to install django_typer as an app if you want to use the shellcompletion command to [enable tab-completion](https://django-typer.readthedocs.io/en/latest/shell_completion.html) or if you would like django-typer to install [rich traceback rendering](https://django-typer.readthedocs.io/en/latest/howto.html#configure-rich-stack-traces) for you - which it does by default if rich is also installed.*
@@ -0,0 +1,301 @@
1
+ r"""
2
+ ::
3
+
4
+ ____ _ ____ __ _
5
+ / __ \ (_)___ _____ ____ _____ / __ \____ __ __/ /_(_)___ ___ _____
6
+ / / / / / / __ `/ __ \/ __ `/ __ \ / /_/ / __ \/ / / / __/ / __ \/ _ \/ ___/
7
+ / /_/ / / / /_/ / / / / /_/ / /_/ / / _, _/ /_/ / /_/ / /_/ / / / / __(__ )
8
+ /_____/_/ /\__,_/_/ /_/\__, /\____/ /_/ |_|\____/\__,_/\__/_/_/ /_/\___/____/
9
+ /___/ /____/
10
+
11
+
12
+ A simple Django app that allows you to specify batches of commands in your settings files
13
+ and then run them in sequence by name using the provied ``routine`` command.
14
+ """
15
+
16
+ import bisect
17
+ import sys
18
+ import typing as t
19
+ from dataclasses import asdict, dataclass, field
20
+
21
+ from django.core.exceptions import ImproperlyConfigured
22
+ from django.utils.functional import Promise
23
+
24
+ VERSION = (1, 0, 0)
25
+
26
+ __title__ = "Django Routines"
27
+ __version__ = ".".join(str(i) for i in VERSION)
28
+ __author__ = "Brian Kohan"
29
+ __license__ = "MIT"
30
+ __copyright__ = "Copyright 2024 Brian Kohan"
31
+
32
+ __all__ = [
33
+ "ROUTINE_SETTING",
34
+ "RoutineCommand",
35
+ "Routine",
36
+ "routine",
37
+ "command",
38
+ "get_routine",
39
+ "routines",
40
+ ]
41
+
42
+
43
+ ROUTINE_SETTING = "DJANGO_ROUTINES"
44
+
45
+
46
+ R = t.TypeVar("R")
47
+
48
+
49
+ @dataclass
50
+ class RoutineCommand:
51
+ """
52
+ Dataclass to hold the routine command information.
53
+ """
54
+
55
+ command: t.Union[str, t.Tuple[str, ...]]
56
+ """
57
+ The command and its arguments to run the routine, all strings or
58
+ coercible to strings that the command will parse correctly.
59
+ """
60
+
61
+ priority: int = 0
62
+ """
63
+ The order of the command in the routine. Priority ties will be run in
64
+ insertion order.
65
+ """
66
+
67
+ switches: t.Tuple[str, ...] = tuple()
68
+ """
69
+ The command will run only when one of these switches is active,
70
+ or for all invocations of the routine if no switches are configured.
71
+ """
72
+
73
+ options: t.Dict[str, t.Any] = field(default_factory=dict)
74
+ """
75
+ t.Any options to pass to the command via call_command.
76
+ """
77
+
78
+ @property
79
+ def command_name(self) -> str:
80
+ return self.command if isinstance(self.command, str) else self.command[0]
81
+
82
+ @property
83
+ def command_args(self) -> t.Tuple[str, ...]:
84
+ return tuple() if isinstance(self.command, str) else self.command[1:]
85
+
86
+ @property
87
+ def command_str(self) -> str:
88
+ return self.command if isinstance(self.command, str) else " ".join(self.command)
89
+
90
+ @classmethod
91
+ def from_dict(
92
+ cls, obj: t.Union["RoutineCommand", t.Dict[str, t.Any]]
93
+ ) -> "RoutineCommand":
94
+ """
95
+ Return a RoutineCommand object from a dictionary representing it.
96
+ """
97
+ return obj if isinstance(obj, RoutineCommand) else RoutineCommand(**obj)
98
+
99
+
100
+ def _insort_right_with_key(a: t.List[R], x: R, key: t.Callable[[R], t.Any]) -> None:
101
+ """
102
+ A function that implements bisect.insort_right with a key callable on items.
103
+
104
+ todo: remove this and replace with key argument to bisect.insort_right when support for
105
+ python <3.10 dropped.
106
+ """
107
+ transformed_list = [key(item) for item in a]
108
+ transformed_x = key(x)
109
+ insert_point = bisect.bisect_right(transformed_list, transformed_x)
110
+ a.insert(insert_point, x)
111
+
112
+
113
+ @dataclass
114
+ class Routine:
115
+ """
116
+ Dataclass to hold the routine information.
117
+ """
118
+
119
+ name: str
120
+ """
121
+ The name of the routine.
122
+ """
123
+
124
+ help_text: t.Union[str, Promise]
125
+ """
126
+ The help text to display for the routine.
127
+ """
128
+
129
+ commands: t.List[RoutineCommand] = field(default_factory=list)
130
+ """
131
+ The commands to run in the routine.
132
+ """
133
+
134
+ switch_helps: t.Dict[str, t.Union[str, Promise]] = field(default_factory=dict)
135
+
136
+ def __len__(self):
137
+ return len(self.commands)
138
+
139
+ @property
140
+ def switches(self) -> t.List[str]:
141
+ switches: t.Set[str] = set()
142
+ for command in self.commands:
143
+ if command.switches:
144
+ switches.update(command.switches)
145
+ return sorted(switches)
146
+
147
+ def plan(self, switches: t.Set[str]) -> t.List[RoutineCommand]:
148
+ return [
149
+ command
150
+ for command in self.commands
151
+ if not command.switches
152
+ or any(switch in switches for switch in command.switches)
153
+ ]
154
+
155
+ def add(self, command: RoutineCommand):
156
+ # python >= 3.10
157
+ # bisect.insort(self.commands, command, key=lambda cmd: cmd.priority)
158
+ _insort_right_with_key(
159
+ self.commands, command, key=lambda cmd: cmd.priority or 0
160
+ )
161
+ return command
162
+
163
+ @classmethod
164
+ def from_dict(cls, obj: t.Union["Routine", t.Dict[str, t.Any]]) -> "Routine":
165
+ """
166
+ Return a RoutineCommand object from a dictionary representing it.
167
+ """
168
+ if isinstance(obj, Routine):
169
+ return obj
170
+ return Routine(
171
+ **{attr: val for attr, val in obj.items() if attr != "commands"},
172
+ commands=[RoutineCommand.from_dict(cmd) for cmd in obj.get("commands", [])],
173
+ )
174
+
175
+
176
+ def routine(
177
+ name: str,
178
+ help_text: t.Union[str, Promise] = "",
179
+ *commands: RoutineCommand,
180
+ **switch_helps,
181
+ ):
182
+ """
183
+ Register a routine to the t.List of routines in settings to be run.
184
+
185
+ :param name: The name of the routine to register.
186
+ :param help_text: The help text to display for the routine by the routines command.
187
+ :param commands: The commands to run in the routine.
188
+ """
189
+ settings = sys._getframe(1).f_globals # noqa: WPS437
190
+ if not settings.get(ROUTINE_SETTING, {}):
191
+ settings[ROUTINE_SETTING] = {}
192
+
193
+ existing: t.List[RoutineCommand] = []
194
+ try:
195
+ routine = get_routine(name)
196
+ help_text = (
197
+ help_text
198
+ # don't trigger translation - we're in settings!
199
+ if isinstance(help_text, Promise) or help_text
200
+ else routine.help_text
201
+ )
202
+ switch_helps = {**routine.switch_helps, **switch_helps}
203
+ existing = routine.commands
204
+ except KeyError:
205
+ pass
206
+ routine = Routine(
207
+ name, help_text=help_text, commands=existing, switch_helps=switch_helps
208
+ )
209
+
210
+ for command in commands:
211
+ routine.add(command)
212
+ settings[ROUTINE_SETTING][name] = asdict(routine)
213
+
214
+
215
+ def command(
216
+ routine: str,
217
+ *command: str,
218
+ priority: int = RoutineCommand.priority,
219
+ switches: t.Optional[t.Sequence[str]] = RoutineCommand.switches,
220
+ **options,
221
+ ):
222
+ """
223
+ Add a routine to the list of routines in settings to be run.
224
+
225
+ .. note::
226
+
227
+ You must call this function from a settings file.
228
+
229
+ :param routine: The name of the routine the command belongs to.
230
+ :param command: The command and its arguments to run the routine, all strings or
231
+ coercible to strings that the command will parse correctly.
232
+ :param priority: The order of the command in the routine. Priority ties will be run in
233
+ insertion order (defaults to zero).
234
+ :param switches: The command will run only when one of these switches is active,
235
+ or for all invocations of the routine if no switches are configured.
236
+ :param options: t.Any options to pass to the command via call_command.
237
+ :return: The new command.
238
+ """
239
+ settings = sys._getframe(1).f_globals # noqa: WPS437
240
+ settings[ROUTINE_SETTING] = settings.get(ROUTINE_SETTING, {}) or {}
241
+ routine_dict = settings[ROUTINE_SETTING]
242
+ routine_obj = (
243
+ Routine.from_dict(routine_dict[routine])
244
+ if routine in routine_dict
245
+ else Routine(routine, "", [])
246
+ )
247
+ new_cmd = routine_obj.add(
248
+ RoutineCommand(
249
+ t.cast(t.Tuple[str], command), priority, tuple(switches or []), options
250
+ )
251
+ )
252
+ routine_dict[routine] = asdict(routine_obj)
253
+ return new_cmd
254
+
255
+
256
+ def get_routine(name: str) -> Routine:
257
+ """
258
+ Get the routine by name.
259
+
260
+ .. note::
261
+
262
+ If called before settings have been configured, this function must be called from settings.
263
+
264
+ :param name: The name of the routine to get.
265
+ :return: The routine.
266
+ :raises: KeyError if the routine does not exist, or routines have not been
267
+ configured.
268
+ :raises: ImproperlyConfigured if the DJANGO_ROUTINES settings variable is not valid.
269
+ """
270
+ from django.conf import settings
271
+
272
+ try:
273
+ if not settings.configured:
274
+ Routine.from_dict(sys._getframe(1).f_globals.get(ROUTINE_SETTING, {})[name]) # noqa: WPS437
275
+ return Routine.from_dict(getattr(settings, ROUTINE_SETTING, {})[name])
276
+ except TypeError as err:
277
+ raise ImproperlyConfigured(
278
+ f"{ROUTINE_SETTING} routine {name} is malformed."
279
+ ) from err
280
+
281
+
282
+ def routines() -> t.Generator[Routine, None, None]:
283
+ """
284
+ A generator that yields Routine objects from settings.
285
+ :yield: Routine objects
286
+ :raises: ImproperlyConfigured if the DJANGO_ROUTINES settings variable is not valid.
287
+ """
288
+ from django.conf import settings
289
+
290
+ routines = (
291
+ sys._getframe(1).f_globals.get(ROUTINE_SETTING, {}) # noqa: WPS437
292
+ if not settings.configured
293
+ else getattr(settings, ROUTINE_SETTING, {})
294
+ ) or {}
295
+ for name, routine in routines.items():
296
+ try:
297
+ yield Routine.from_dict(routine)
298
+ except TypeError as err:
299
+ raise ImproperlyConfigured(
300
+ f"{ROUTINE_SETTING} routine {name} is malformed."
301
+ ) from err
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DjangoRoutinesConfig(AppConfig):
5
+ name = "django_routines"
6
+ verbose_name = "Django Routines"
@@ -0,0 +1,201 @@
1
+ import typing as t
2
+ from importlib.util import find_spec
3
+
4
+ import click
5
+ import typer
6
+ from django.core.management import CommandError, call_command
7
+ from django.core.management.base import BaseCommand
8
+ from django.utils.translation import gettext as _
9
+ from django_typer import TyperCommand, get_command, initialize
10
+ from django_typer.types import Verbosity
11
+
12
+ from django_routines import (
13
+ Routine,
14
+ RoutineCommand,
15
+ get_routine,
16
+ routines,
17
+ )
18
+
19
+ width = 80
20
+ use_rich = find_spec("rich") is not None
21
+ if use_rich:
22
+ from rich.console import Console
23
+
24
+ width = Console().width
25
+
26
+
27
+ COMMAND_TMPL = """
28
+ import sys
29
+ if sys.version_info < (3, 9):
30
+ from typing_extensions import Annotated
31
+ else:
32
+ from typing import Annotated
33
+
34
+ def {routine}(
35
+ self,
36
+ context: typer.Context,
37
+ all: Annotated[bool, typer.Option("--all", help="{all_help}")] = False,
38
+ {switch_args}
39
+ ):
40
+ self.routine = "{routine}"
41
+ self.switches = []
42
+ {add_switches}
43
+ if not context.invoked_subcommand:
44
+ return self._run_routine()
45
+ return self.{routine}
46
+ """
47
+
48
+
49
+ class Command(TyperCommand, rich_markup_mode="rich"): # type: ignore
50
+ """
51
+ A TyperCommand_
52
+ """
53
+
54
+ help = _("Run batches of commands configured in settings.")
55
+
56
+ verbosity: int = 1
57
+ switches: t.Set[str] = set()
58
+
59
+ suppressed_base_arguments = set()
60
+
61
+ _routine: t.Optional[Routine] = None
62
+ _verbosity_passed: bool = False
63
+
64
+ @property
65
+ def routine(self) -> t.Optional[Routine]:
66
+ return self._routine
67
+
68
+ @routine.setter
69
+ def routine(self, routine: t.Union[str, Routine]):
70
+ self._routine = (
71
+ routine if isinstance(routine, Routine) else get_routine(str(routine))
72
+ )
73
+
74
+ @property
75
+ def plan(self) -> t.List[RoutineCommand]:
76
+ assert self.routine
77
+ return self.routine.plan(self.switches)
78
+
79
+ @initialize()
80
+ def init(self, ctx: typer.Context, verbosity: Verbosity = verbosity):
81
+ self.verbosity = verbosity
82
+ self._pass_verbosity = (
83
+ ctx.get_parameter_source("verbosity")
84
+ is not click.core.ParameterSource.DEFAULT
85
+ )
86
+
87
+ def _run_routine(self):
88
+ assert self.routine
89
+ for command in self.plan:
90
+ if self.verbosity > 0:
91
+ self.secho(command.command_str, fg="cyan")
92
+ try:
93
+ cmd = get_command(
94
+ command.command_name,
95
+ BaseCommand,
96
+ stdout=t.cast(t.IO[str], self.stdout._out),
97
+ stderr=t.cast(t.IO[str], self.stderr._out),
98
+ force_color=self.force_color,
99
+ no_color=self.no_color,
100
+ )
101
+ options = command.options
102
+ if (
103
+ self._pass_verbosity
104
+ and not any(
105
+ "verbosity" in arg
106
+ for arg in getattr(cmd, "suppressed_base_arguments", [])
107
+ )
108
+ and not any("--verbosity" in arg for arg in command.command_args)
109
+ ):
110
+ # only pass verbosity if it was passed to routines, not suppressed
111
+ # by the command class and not passed by the configured command
112
+ options = {"verbosity": self.verbosity, **options}
113
+ call_command(cmd, *command.command_args, **options)
114
+ except KeyError:
115
+ raise CommandError(f"Command not found: {command.command_name}")
116
+
117
+ def _list(self) -> None:
118
+ for command in self.plan:
119
+ priority = str(command.priority)
120
+ cmd_str = command.command_str
121
+ switches_str = " | " if command.switches else ""
122
+ opt_str = " ".join([f"{k}={v}" for k, v in command.options.items()])
123
+ if self.force_color or not self.no_color:
124
+ priority = click.style(priority, fg="green")
125
+ cmd_str = click.style(cmd_str, fg="cyan", bold=True)
126
+ opt_str = " ".join(
127
+ [
128
+ f"{click.style(k, 'blue')}={click.style(v, 'magenta')}"
129
+ for k, v in command.options.items()
130
+ ]
131
+ )
132
+ switches_str += ", ".join(
133
+ click.style(switch, fg="yellow")
134
+ for switch in (command.switches or [])
135
+ )
136
+ else:
137
+ switches_str += ", ".join(command.switches or [])
138
+
139
+ opt_str = f" ({opt_str})" if opt_str else ""
140
+ self.secho(f"[{priority}] {cmd_str}{opt_str}{switches_str}")
141
+
142
+
143
+ for routine in routines():
144
+ switches = routine.switches
145
+ switch_args = ", ".join(
146
+ [
147
+ f"{switch}: Annotated[bool, typer.Option('--{switch}', help='{routine.switch_helps.get(switch, '')}')] = False"
148
+ for switch in switches
149
+ ]
150
+ )
151
+ add_switches = ""
152
+ for switch in switches:
153
+ add_switches += f'\n if all or {switch}: self.switches.append("{switch}")'
154
+
155
+ cmd_code = COMMAND_TMPL.format(
156
+ routine=routine.name,
157
+ switch_args=switch_args,
158
+ add_switches=add_switches,
159
+ all_help=_("Include all switched commands."),
160
+ )
161
+
162
+ command_strings = []
163
+ for command in routine.commands:
164
+ priority = f"{'[green]' if use_rich else ''}{command.priority}{'[/green]' if use_rich else ''}"
165
+ cmd_str = f"{'[cyan]' if use_rich else ''}{command.command_str}{'[/cyan]' if use_rich else ''}"
166
+ if command.options:
167
+ if use_rich:
168
+ opt_str = " ".join(
169
+ [
170
+ f"[blue]{k}[/blue]=[magenta]{v}[/magenta]"
171
+ for k, v in command.options.items()
172
+ ]
173
+ )
174
+ else:
175
+ opt_str = " ".join([f"{k}={v}" for k, v in command.options.items()])
176
+ cmd_str += f" ({opt_str})"
177
+ switches_str = " | " if command.switches else ""
178
+ switches_str += ", ".join(
179
+ f"{'[yellow]' if use_rich else ''}{switch}{'[/yellow]' if use_rich else ''}"
180
+ for switch in (command.switches or [])
181
+ )
182
+ command_strings.append(f"[{priority}] {cmd_str}{switches_str}")
183
+
184
+ exec(cmd_code)
185
+
186
+ if not use_rich:
187
+ width = max([len(cmd) for cmd in command_strings])
188
+ ruler = f"[underline]{' ' * width}[/underline]\n" if use_rich else "-" * width
189
+ cmd_strings = "\n".join(command_strings)
190
+ cmd_strings = f"{'[bright]' if use_rich else ''}{cmd_strings}{'[/bright]' if use_rich else ''}"
191
+ lb = "\b\n"
192
+ help_txt = (
193
+ f"{lb}{routine.help_text}\n{ruler}{lb}{'' if use_rich else lb}{cmd_strings}\n"
194
+ )
195
+ grp = Command.group(
196
+ help=help_txt, short_help=routine.help_text, invoke_without_command=True
197
+ )(locals()[routine.name])
198
+
199
+ @grp.command(name="list", help=_("List the commands that will be run."))
200
+ def list(self):
201
+ self._list()
@@ -0,0 +1,138 @@
1
+ [tool.poetry]
2
+ name = "django-routines"
3
+ version = "1.0.0"
4
+ description = "Configure named groups of management commands in Django settings files."
5
+ authors = ["Brian Kohan <bckohan@gmail.com>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ repository = "https://github.com/bckohan/django-routines"
9
+ homepage = "https://django-routines.readthedocs.io"
10
+ keywords = ["django", "CLI", "management", "routine", "routines", "batch", "commands", "deploy"]
11
+ classifiers = [
12
+ "Environment :: Console",
13
+ "Framework :: Django",
14
+ "Operating System :: OS Independent",
15
+ "Topic :: Software Development :: Libraries :: Python Modules",
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Framework :: Django :: 3.2",
18
+ "Framework :: Django :: 4.0",
19
+ "Framework :: Django :: 4.1",
20
+ "Framework :: Django :: 4.2",
21
+ "Framework :: Django :: 5.0",
22
+ "Intended Audience :: Developers",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Natural Language :: English",
25
+ "Programming Language :: Python",
26
+ "Programming Language :: Python :: 3.8",
27
+ "Programming Language :: Python :: 3.9",
28
+ "Programming Language :: Python :: 3.10",
29
+ "Programming Language :: Python :: 3.11",
30
+ "Programming Language :: Python :: 3.12",
31
+ "Topic :: Internet :: WWW/HTTP",
32
+ "Topic :: Internet :: WWW/HTTP :: Site Management",
33
+ "Topic :: Software Development :: Libraries",
34
+ "Topic :: Software Development :: Libraries :: Python Modules"
35
+ ]
36
+
37
+ packages = [
38
+ { include = "django_routines" }
39
+ ]
40
+ exclude = ["tests"]
41
+
42
+ [tool.poetry.dependencies]
43
+ python = ">=3.8,<4.0"
44
+ Django = ">=3.2,<6.0"
45
+ django-typer = "^2.0.2"
46
+
47
+ # this should track typer's rich dependency, so long as our console
48
+ # patches still work - so be sure to test on the low end of the range
49
+ rich = { version = ">=10.11.0,<14.0.0", optional = true }
50
+
51
+ # we need this on 3.8 for Annotated types and 3.9 for ParamSpec
52
+ typing-extensions = { version = ">=3.7.4.3", markers = "python_version < '3.10'" }
53
+
54
+
55
+ [tool.poetry.group.dev.dependencies]
56
+ ipdb = "^0.13.13"
57
+ pytest-django = "^4.7.0"
58
+ pytest-cov = "^5.0.0"
59
+ Sphinx = [
60
+ { version = "^7.2.0", markers = "python_version > '3.8'" },
61
+ { version = "^7.0.0", markers = "python_version <= '3.8'" },
62
+ ]
63
+ sphinx-rtd-theme = "^2.0.0"
64
+ doc8 = "^1.1.1"
65
+ aiohttp = "^3.9.1"
66
+ readme-renderer = {extras = ["md"], version = ">=42,<44"}
67
+ sphinxcontrib-typer = {extras = ["html", "pdf", "png"], version = "^0.3.0", markers="python_version >= '3.9'"}
68
+ pytest-env = "^1.0.0"
69
+ pexpect = "^4.9.0"
70
+ pyright = "^1.1.357"
71
+ ruff = "^0.4.1"
72
+ django-stubs = "^5.0.2"
73
+ mypy = "^1.10.0"
74
+
75
+ [tool.poetry.extras]
76
+ rich = ["rich"]
77
+
78
+ [tool.mypy]
79
+ # The mypy configurations: http://bit.ly/2zEl9WI
80
+ # todo some stubs errors
81
+ ignore_missing_imports = true
82
+ exclude = ["tests"]
83
+
84
+
85
+ # todo doc8 configuration here is not being picked up and doesnt seem to be working
86
+ # as expected - for now pass these parameters manually
87
+ [tool.doc8]
88
+ max-line-length = 100
89
+ sphinx = true
90
+
91
+ [tool.pytest.ini_options]
92
+ # py.test options:
93
+ DJANGO_SETTINGS_MODULE = "tests.settings"
94
+ python_files = "test_*.py"
95
+ norecursedirs = "*.egg .eggs dist build docs .tox .git __pycache__ shellcompletion"
96
+ env = [
97
+ "TERMINAL_WIDTH=80",
98
+ ]
99
+
100
+ addopts = [
101
+ "--strict-markers",
102
+ "--cov=django_routines",
103
+ "--cov-branch",
104
+ "--cov-report=term-missing:skip-covered"
105
+ ]
106
+
107
+ [tool.coverage.run]
108
+ omit = ["tests/**/*.py"]
109
+ branch = true
110
+ source = ["tests"]
111
+ concurrency = ["multiprocessing"]
112
+ parallel = true
113
+ relative_files = true
114
+ command_line = "-m pytest --cov=django_routines"
115
+
116
+ [tool.coverage.paths]
117
+ source = [
118
+ "django_routines"
119
+ ]
120
+
121
+ [tool.pyright]
122
+ exclude = ["tests/**/*"]
123
+ include = [
124
+ "django_routines"
125
+ ]
126
+
127
+ [tool.ruff]
128
+ line-length = 88
129
+ exclude = [
130
+ "doc",
131
+ "dist",
132
+ "examples"
133
+ ]
134
+
135
+ [tool.ruff.lint]
136
+ exclude = [
137
+ "tests/**/*"
138
+ ]