-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap.py
219 lines (180 loc) · 6.56 KB
/
bootstrap.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
""" Run this script directly after cloning the project. """
import os
import os.path as op
import platform
import sys
import subprocess
import shlex
SLUG = 'lettercraft'
WINDOWS = (platform.system() == 'Windows')
VIRTUALENV_BINDIR = 'Scripts' if WINDOWS else 'bin'
LOGFILE_NAME = 'bootstrap.log'
class Command(object):
""" Representation of a command to be run in project setup.
We create a bunch of these to implement most of the steps in main.
"""
@classmethod
def get_log(cls):
if not hasattr(cls, 'log'):
cls.log = open(LOGFILE_NAME, 'w', buffering=1)
return cls.log
def __init__(self, description, command, *args, **kwargs):
self.description = description
if isinstance(command, str):
command = shlex.split(command)
self.command = command
self.args = args
if 'stdout' not in kwargs:
kwargs['stdout'] = self.get_log()
if 'stderr' not in kwargs:
kwargs['stderr'] = subprocess.STDOUT
self.kwargs = kwargs
def __call__(self):
log = self.get_log()
print('{}... '.format(self.description), end='', flush=True)
log.write('$ {}\n\n'.format(self))
try:
exit_code = subprocess.call(self.command, *self.args, **self.kwargs)
if exit_code != 0:
print('failed ({}).'.format(exit_code))
return False
print('success.')
log.write('\n\n')
return True
except Exception as e:
print(e)
log.write('never ran (exception)\n\n')
return False
def __str__(self):
representation = ' '.join(map(shlex.quote, self.command))
if 'cwd' in self.kwargs:
return '(cd {} ; {})'.format(self.kwargs['cwd'], representation)
return representation
def main(argv):
already_in_project, cd_into_project = prepare_cwd()
venv, create_virtualenv, activate_venv = prepare_virtualenv()
pip_tools = backpack = False
if venv:
pip_tools = install_pip_tools()
backpack = install_backend_packages()
frontpack = install_frontend_packages()
db, create_db = prepare_db()
migrate = superuser = False
if db and backpack:
migrate = run_migrations()
if migrate:
superuser = create_superuser()
main_branch = track_main()
gitflow = False
if main_branch:
gitflow = setup_gitflow()
if not all([gitflow, superuser, frontpack, pip_tools]):
print('\nPlease read {} for information on failed commands.'.format(LOGFILE_NAME))
print('\nAlmost ready to go! Just a couple more commands to run:')
if not already_in_project: print(cd_into_project)
if not venv: print(create_virtualenv)
print(activate_venv)
if not (pip_tools and backpack and frontpack):
print(install_all_packages)
if not db: print(create_db)
if not migrate: print(run_migrations)
if not superuser: print(create_superuser)
if not main_branch: print(track_main)
if not gitflow: print(setup_gitflow)
print(yarn_start)
def prompt(variable, default_value):
return input('{} [{}]: '.format(variable, default_value)) or default_value
def prepare_cwd():
invocation_dir = op.abspath(os.getcwd())
project_root = op.dirname(op.abspath(__file__))
if invocation_dir == project_root:
return True, None
os.chdir(project_root)
relative_path = op.relpath(project_root, invocation_dir)
cd_into_project = Command('', ['cd', relative_path])
return False, cd_into_project
def prepare_virtualenv():
default_env = '.env'
env_path = prompt('virtualenv', default_env)
default_cmd = 'virtualenv {} --prompt="({}) "'.format(env_path, SLUG)
env_cmd = prompt('virtualenv_command', default_cmd)
create_command = make_create_venv_command(env_cmd)
activate_command = make_activate_venv_command(env_path)
success = create_command()
if success:
adopt_virtualenv(env_path)
return success, create_command, activate_command
def make_create_venv_command(venv_cmd):
return Command('Create the virtualenv', venv_cmd)
def make_activate_venv_command(venv_path):
activate_helper = ([] if WINDOWS else ['source'])
return Command(
'',
activate_helper + [op.join(venv_path, VIRTUALENV_BINDIR, 'activate')],
)
def adopt_virtualenv(env_path):
""" Enable the virtualenv for our own subprocesses. """
# first lines are a quick imitation of a local bin/activate script
venv_abs = op.abspath(env_path)
os.environ['VIRTUAL_ENV'] = venv_abs
python_bindir = op.join(venv_abs, VIRTUALENV_BINDIR)
os.environ['PATH'] = os.pathsep.join([python_bindir, os.environ['PATH']])
os.environ.pop('PYTHONHOME', None)
# next line is a fix for https://bugs.python.org/issue22490
os.environ.pop('__PYVENV_LAUNCHER__', None)
def prepare_db():
default_cmd = 'psql'
psql_cmd = prompt('psql_command', default_cmd)
create_command = make_create_db_command(psql_cmd)
success = create_command()
return success, create_command
def make_create_db_command(psql_cmd):
# psql does not properly indicate failure; it always exits with 0.
# Fortunately, it is one of the last commands.
return Command(
'Create the database',
psql_cmd + ' -f ' + op.join('backend', 'create_db.sql'),
)
install_pip_tools = Command(
'Install pip-tools',
['yarn', 'preinstall'],
)
install_backend_packages = Command(
'Install the backend requirements',
['yarn', 'install-back'],
)
install_frontend_packages = Command(
'Install the frontend packages',
['yarn', 'fyarn'],
)
install_all_packages = Command('Install all packages', ['yarn'])
run_migrations = Command(
'Run the initial migrations',
['yarn', 'django', 'migrate'],
)
# Github Actions sets "CI" environment variable
if os.environ.get('CI'):
create_superuser = Command(
'Skip creating the superuser',
['yarn', 'back', ':'], # ':' for no-op
stdout=None, # share stdout and stderr with this process
stderr=None,
)
else:
create_superuser = Command(
'Create the superuser',
['yarn', 'django', 'createsuperuser'],
stdout=None, # share stdout and stderr with this process
stderr=None,
)
track_main = Command(
'Create origin-tracking main branch',
['git', 'branch', '--track', 'main', 'origin/main'],
)
setup_gitflow = Command(
'Initialize git-flow',
['git', 'flow', 'init', '-d'],
)
yarn_start = Command('', ['yarn', 'start'])
if __name__ == '__main__':
sys.exit(main(sys.argv))