about summary refs log tree commit diff
path: root/nixpkgs/pkgs/development/python-modules/ihatemoney/remove_flask_script.patch
blob: dac59680a09cc39b55b2b7e60ba20f6fb27064bb (plain) (blame)
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
commit 4d831ba2316d54f4916fb9d1160ec7a3856b47d4
Author: Glandos <bugs-github@antipoul.fr>
Date:   Sun Jun 6 14:30:52 2021 +0200

    remove usage of Flask-Script
    
    Use flask.cli instead with compatibility layer for existing commands,
    such as "runserver".
    
    cherry-pick from 74e222f1a1cbfc2fac102fefc1115e9d0a6586dc

diff --git a/Makefile b/Makefile
index a681709..90ab1bb 100644
--- a/Makefile
+++ b/Makefile
@@ -38,7 +38,7 @@ update: remove-install-stamp install ## Update the dependencies
 .PHONY: serve
 serve: install ## Run the ihatemoney server
 	@echo 'Running ihatemoney on http://localhost:5000'
-	$(PYTHON) -m ihatemoney.manage runserver
+	$(PYTHON) -m ihatemoney.manage run
 
 .PHONY: test
 test: install-dev ## Run the tests
diff --git a/docs/installation.rst b/docs/installation.rst
index 4994499..4df70a2 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -59,7 +59,7 @@ Test it
 
 Once installed, you can start a test server::
 
-  ihatemoney runserver
+  ihatemoney run
 
 And point your browser at `http://localhost:5000 <http://localhost:5000>`_.
 
diff --git a/ihatemoney/manage.py b/ihatemoney/manage.py
index a192844..805a07f 100755
--- a/ihatemoney/manage.py
+++ b/ihatemoney/manage.py
@@ -5,8 +5,8 @@ import os
 import random
 import sys
 
-from flask_migrate import Migrate, MigrateCommand
-from flask_script import Command, Manager, Option
+import click
+from flask.cli import FlaskGroup
 from werkzeug.security import generate_password_hash
 
 from ihatemoney.models import Project, db
@@ -14,31 +14,48 @@ from ihatemoney.run import create_app
 from ihatemoney.utils import create_jinja_env
 
 
-class GeneratePasswordHash(Command):
+@click.group(cls=FlaskGroup, create_app=create_app)
+def cli():
+    """IHateMoney Management script"""
 
-    """Get password from user and hash it without printing it in clear text."""
 
-    def run(self):
-        password = getpass.getpass(prompt="Password: ")
-        print(generate_password_hash(password))
-
-
-class GenerateConfig(Command):
-    def get_options(self):
-        return [
-            Option(
-                "config_file",
-                choices=[
-                    "ihatemoney.cfg",
-                    "apache-vhost.conf",
-                    "gunicorn.conf.py",
-                    "supervisord.conf",
-                    "nginx.conf",
-                ],
-            )
+@cli.command(
+    context_settings={"ignore_unknown_options": True, "allow_extra_args": True}
+)
+@click.pass_context
+def runserver(ctx):
+    """Deprecated, use the "run" command instead"""
+    click.secho(
+        '"runserver" is deprecated, please use the standard "run" flask command',
+        fg="red",
+    )
+    run = cli.get_command(ctx, "run")
+    ctx.forward(run)
+
+
+@click.command(name="generate_password_hash")
+def password_hash():
+    """Get password from user and hash it without printing it in clear text."""
+    password = getpass.getpass(prompt="Password: ")
+    print(generate_password_hash(password))
+
+
+@click.command()
+@click.argument(
+    "config_file",
+    type=click.Choice(
+        [
+            "ihatemoney.cfg",
+            "apache-vhost.conf",
+            "gunicorn.conf.py",
+            "supervisord.conf",
+            "nginx.conf",
         ]
+    ),
+)
+def generate_config(config_file):
+    """Generate front-end server configuration"""
 
-    @staticmethod
     def gen_secret_key():
         return "".join(
             [
@@ -49,59 +66,33 @@ class GenerateConfig(Command):
             ]
         )
 
-    def run(self, config_file):
-        env = create_jinja_env("conf-templates", strict_rendering=True)
-        template = env.get_template("%s.j2" % config_file)
+    env = create_jinja_env("conf-templates", strict_rendering=True)
+    template = env.get_template(f"{config_file}.j2")
 
-        bin_path = os.path.dirname(sys.executable)
-        pkg_path = os.path.abspath(os.path.dirname(__file__))
+    bin_path = os.path.dirname(sys.executable)
+    pkg_path = os.path.abspath(os.path.dirname(__file__))
 
-        print(
-            template.render(
-                pkg_path=pkg_path,
-                bin_path=bin_path,
-                sys_prefix=sys.prefix,
-                secret_key=self.gen_secret_key(),
-            )
+    print(
+        template.render(
+            pkg_path=pkg_path,
+            bin_path=bin_path,
+            sys_prefix=sys.prefix,
+            secret_key=gen_secret_key(),
         )
-
-
-class DeleteProject(Command):
-    def run(self, project_name):
-        demo_project = Project.query.get(project_name)
-        db.session.delete(demo_project)
+    )
+
+
+@cli.command()
+@click.argument("project_name")
+def delete_project(project_name):
+    """Delete a project"""
+    project = Project.query.get(project_name)
+    if project is None:
+        click.secho(f'Project "{project_name}" not found', fg="red")
+    else:
+        db.session.delete(project)
         db.session.commit()
 
 
-def main():
-    QUIET_COMMANDS = ("generate_password_hash", "generate-config")
-
-    exception = None
-    backup_stderr = sys.stderr
-    # Hack to divert stderr for commands generating content to stdout
-    # to avoid confusing the user
-    if len(sys.argv) > 1 and sys.argv[1] in QUIET_COMMANDS:
-        sys.stderr = open(os.devnull, "w")
-
-    try:
-        app = create_app()
-        Migrate(app, db)
-    except Exception as e:
-        exception = e
-
-    # Restore stderr
-    sys.stderr = backup_stderr
-
-    if exception:
-        raise exception
-
-    manager = Manager(app)
-    manager.add_command("db", MigrateCommand)
-    manager.add_command("generate_password_hash", GeneratePasswordHash)
-    manager.add_command("generate-config", GenerateConfig)
-    manager.add_command("delete-project", DeleteProject)
-    manager.run()
-
-
 if __name__ == "__main__":
-    main()
+    cli()
diff --git a/ihatemoney/tests/tests.py b/ihatemoney/tests/tests.py
index b27fafc..23f19a6 100644
--- a/ihatemoney/tests/tests.py
+++ b/ihatemoney/tests/tests.py
@@ -15,7 +15,7 @@ from sqlalchemy import orm
 from werkzeug.security import check_password_hash, generate_password_hash
 
 from ihatemoney import history, models, utils
-from ihatemoney.manage import DeleteProject, GenerateConfig, GeneratePasswordHash
+from ihatemoney.manage import delete_project, generate_config, password_hash
 from ihatemoney.run import create_app, db, load_configuration
 from ihatemoney.versioning import LoggingMode
 
@@ -2157,28 +2157,24 @@ class CommandTestCase(BaseTestCase):
         - raise no exception
         - produce something non-empty
         """
-        cmd = GenerateConfig()
-        for config_file in cmd.get_options()[0].kwargs["choices"]:
-            with patch("sys.stdout", new=io.StringIO()) as stdout:
-                cmd.run(config_file)
-                print(stdout.getvalue())
-                self.assertNotEqual(len(stdout.getvalue().strip()), 0)
+        runner = self.app.test_cli_runner()
+        for config_file in generate_config.params[0].type.choices:
+            result = runner.invoke(generate_config, config_file)
+            self.assertNotEqual(len(result.output.strip()), 0)
 
     def test_generate_password_hash(self):
-        cmd = GeneratePasswordHash()
-        with patch("sys.stdout", new=io.StringIO()) as stdout, patch(
-            "getpass.getpass", new=lambda prompt: "secret"
-        ):  # NOQA
-            cmd.run()
-            print(stdout.getvalue())
-            self.assertEqual(len(stdout.getvalue().strip()), 189)
+        runner = self.app.test_cli_runner()
+        with patch("getpass.getpass", new=lambda prompt: "secret"):
+            result = runner.invoke(password_hash)
+            print(result.output.strip())
+            self.assertEqual(len(result.output.strip()), 102)
 
     def test_demo_project_deletion(self):
         self.create_project("demo")
         self.assertEquals(models.Project.query.get("demo").name, "demo")
 
-        cmd = DeleteProject()
-        cmd.run("demo")
+        runner = self.app.test_cli_runner()
+        runner.invoke(delete_project, "demo")
 
         self.assertEqual(len(models.Project.query.all()), 0)
 
diff --git a/setup.cfg b/setup.cfg
index d493717..48e447c 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -31,7 +31,6 @@ install_requires =
     Flask-Mail==0.9.1
     Flask-Migrate==2.5.3
     Flask-RESTful==0.3.8
-    Flask-Script==2.0.6
     Flask-SQLAlchemy==2.4.1
     Flask-WTF==0.14.3
 	WTForms==2.2.1
@@ -51,8 +50,12 @@ dev =
     zest.releaser==6.20.1
 
 [options.entry_points]
+flask.commands =
+    generate_password_hash = ihatemoney.manage:password_hash
+    generate-config = ihatemoney.manage:generate_config
+
 console_scripts =
-    ihatemoney = ihatemoney.manage:main
+    ihatemoney = ihatemoney.manage:cli
 
 paste.app_factory =
     main = ihatemoney.run:main