-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
__init__.py
274 lines (251 loc) · 7.44 KB
/
__init__.py
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
from datasette import hookimpl
from datasette.publish.common import (
add_common_publish_arguments_and_options,
fail_if_publish_binary_not_installed,
)
from datasette.utils import (
temporary_docker_directory,
value_as_boolean,
ValueAsBooleanError,
)
from subprocess import run
import click
from click.types import CompositeParamType
import json
import os
import pathlib
import re
import shutil
INDEX_PY = """
from datasette.app import Datasette
import json
import pathlib
static_mounts = [
(static, str((pathlib.Path(".") / static).resolve()))
for static in {statics}
]
metadata = dict()
try:
metadata = json.load(open("metadata.json"))
except Exception:
pass
app = Datasette(
[],
{database_files},
static_mounts=static_mounts,
metadata=metadata{extras},
cors=True,
config={settings}
).app()
""".strip()
project_name_re = re.compile(r"^[a-z0-9][a-z0-9-]{1,51}$")
class Setting(CompositeParamType):
name = "setting"
arity = 2
def convert(self, config, param, ctx):
from datasette.app import DEFAULT_SETTINGS
name, value = config
if name not in DEFAULT_SETTINGS:
self.fail(
f"{name} is not a valid option (--help-config to see all)",
param,
ctx,
)
return
# Type checking
default = DEFAULT_SETTINGS[name]
if isinstance(default, bool):
try:
return name, value_as_boolean(value)
except ValueAsBooleanError:
self.fail(f'"{name}" should be on/off/true/false/1/0', param, ctx)
return
elif isinstance(default, int):
if not value.isdigit():
self.fail(f'"{name}" should be an integer', param, ctx)
return
return name, int(value)
elif isinstance(default, str):
return name, value
else:
# Should never happen:
self.fail("Invalid option")
class ProjectName(click.ParamType):
name = "project"
def convert(self, value, param, ctx):
if not project_name_re.match(value):
self.fail(
"Project name must be alphanumeric, max 52 chars, cannot begin with a hyphen"
)
return value
def add_vercel_options(cmd):
for decorator in reversed(
(
click.option("--token", help="Auth token to use for deploy"),
click.option(
"--project",
type=ProjectName(),
help="Vercel project name to use",
required=True,
),
click.option(
"--no-prod",
is_flag=True,
help="Don't deploy directly to production",
),
click.option(
"--debug",
is_flag=True,
help="Enable Vercel CLI debug output",
),
click.option(
"--public",
is_flag=True,
help="Publish source with Vercel CLI --public",
),
click.option(
"--generate-dir",
type=click.Path(dir_okay=True, file_okay=False),
help="Output generated application files here",
),
click.option(
"--setting",
"settings",
type=Setting(),
help="Setting, see docs.datasette.io/en/stable/settings.html",
multiple=True,
),
)
):
cmd = decorator(cmd)
return cmd
def _publish_vercel(
files,
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
plugin_secret,
version_note,
secret,
title,
license,
license_url,
source,
source_url,
about,
about_url,
token,
project,
no_prod,
debug,
public,
generate_dir,
settings,
):
fail_if_publish_binary_not_installed(
"vercel", "Vercel", "https://vercel.com/download"
)
extra_metadata = {
"title": title,
"license": license,
"license_url": license_url,
"source": source,
"source_url": source_url,
"about": about,
"about_url": about_url,
}
if generate_dir:
generate_dir = str(pathlib.Path(generate_dir).resolve())
with temporary_docker_directory(
files,
"datasette-now-v2",
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
False,
version_note,
secret,
extra_metadata,
port=8080,
):
# We don't actually want the Dockerfile
os.remove("Dockerfile")
open("vercel.json", "w").write(
json.dumps(
{
"name": project,
"version": 2,
"builds": [{"src": "index.py", "use": "@vercel/python"}],
"routes": [{"src": "(.*)", "dest": "index.py"}],
},
indent=4,
)
)
extras = []
if template_dir:
extras.append('template_dir="{}"'.format(template_dir))
if plugins_dir:
extras.append('plugins_dir="{}"'.format(plugins_dir))
statics = [item[0] for item in static]
open("index.py", "w").write(
INDEX_PY.format(
database_files=json.dumps([os.path.split(f)[-1] for f in files]),
extras=", {}".format(", ".join(extras)) if extras else "",
statics=json.dumps(statics),
settings=json.dumps(dict(settings) or {}),
)
)
datasette_install = "datasette"
if branch:
datasette_install = (
"https://github.com/simonw/datasette/archive/{}.zip".format(branch)
)
open("requirements.txt", "w").write(
"\n".join([datasette_install, "pysqlite3-binary"] + list(install))
)
if generate_dir:
# Copy these to the specified directory
shutil.copytree(".", generate_dir)
click.echo(
"Your generated application files have been written to:", err=True
)
click.echo(" {}\n".format(generate_dir), err=True)
click.echo("To deploy using Vercel, run the following:")
click.echo(" cd {}".format(generate_dir), err=True)
click.echo(" vercel --prod".format(generate_dir), err=True)
else:
# Run the deploy with Vercel
cmd = ["vercel", "--confirm", "--no-clipboard"]
if debug:
cmd.append("--debug")
if not no_prod:
cmd.append("--prod")
if public:
cmd.append("--public")
if token:
cmd.extend(["--token", token])
# Add the secret
cmd.extend(["--env", "DATASETTE_SECRET={}".format(secret)])
run(cmd)
@hookimpl
def publish_subcommand(publish):
@publish.command()
@add_common_publish_arguments_and_options
@add_vercel_options
def vercel(*args, **kwargs):
"Publish to https://vercel.com/"
_publish_vercel(*args, **kwargs)
@publish.command()
@add_common_publish_arguments_and_options
@add_vercel_options
def now(*args, **kwargs):
"Alias for 'datasette publish vercel'"
_publish_vercel(*args, **kwargs)