-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMakeAppWorkDir.py
More file actions
415 lines (362 loc) · 15.1 KB
/
Copy pathMakeAppWorkDir.py
File metadata and controls
415 lines (362 loc) · 15.1 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/usr/bin/env python3
"""MakeAppWorkDir.py
INTRODUCTION
This utility builds a directory tree that can be used as the current
working directory of an instance of your Webware application.
By using a separate directory tree like this, your application can run
without needing write access etc. to the Webware directory tree, and
you can also run more than one application server at once using the
same Webware code. This makes it easy to reuse and keep Webware
updated without disturbing your applications.
USAGE
MakeAppWorkDir.py [Options] WorkDir
Options:
-c, --context-name=... The name for the pre-installed context.
By default, it will be "MyContext".
-d, --context-dir=... The directory where the context will be located,
so you can place it outside of the WorkDir.
-l, --library=... Other dirs to be included in the search path.
You may specify this option multiple times.
WorkDir:
The target working directory to be created.
"""
import argparse
import glob
import os
import shutil
import webware
defaultContext = 'MyContext'
try:
chown, chmod = shutil.chown, os.chmod
import stat
except (AttributeError, ImportError):
chown = chmod = stat = None
class MakeAppWorkDir:
"""Make a new application runtime directory for Webware.
This class breaks down the steps needed to create a new runtime
directory for Webware. That includes all the needed
subdirectories, default configuration files, and startup scripts.
Each step can be overridden in a derived class if needed.
Existing files will not be overwritten, but access permissions
will be changed accordingly in any case.
"""
def __init__(self, workDir,
contextName=defaultContext, contextDir='', libraryDirs=None,
user=None, group=None, verbose=True):
"""Initializer for MakeAppWorkDir.
Pass in at least the target working directory.
If you pass None for contextName, then the default context
will be the the Examples directory as usual.
"""
self._workDir = os.path.abspath(workDir)
self._contextName = contextName
self._contextDir = contextDir
if libraryDirs is None:
libraryDirs = []
self._libraryDirs = libraryDirs
self._user, self._group = user, group
self._verbose = verbose
self._webwareDir = webware.__path__[0]
def buildWorkDir(self):
"""These are all the steps needed to make a new runtime directory.
You can override the steps taken here with your own methods.
"""
if os.path.exists(self._workDir):
self.msg("The target directory already exists.")
self.msg(
"Adding everything needed for a Webware runtime directory...")
else:
self.msg("Making a new Webware runtime directory...")
self.msg()
self.makeDirectories()
self.copyConfigFiles()
self.copyOtherFiles()
self.setLibDirs()
if self._contextName:
self.makeDefaultContext()
self.addGitIgnore()
self.changeOwner()
self.printCompleted()
def makeDirectories(self):
"""Create all the needed directories if they don't already exist."""
self.msg("Creating the directory tree...")
standardDirs = ('', 'Cache', 'Configs', 'ErrorMsgs', 'Logs',
'Scripts', 'Sessions', 'Static')
for path in standardDirs:
path = os.path.join(self._workDir, path)
if os.path.exists(path):
self.msg(f"\t{path} already exists.")
else:
os.mkdir(path)
self.msg(f"\t{path}")
for path in self._libraryDirs:
path = os.path.join(self._workDir, path)
if os.path.exists(path):
self.msg(f"\t{path} already exists.")
else:
os.makedirs(path)
with open(os.path.join(path, '__init__.py'), 'w',
encoding='ascii') as initFile:
initFile.write('#\n')
self.msg(f"\t{path} created.")
def copyConfigFiles(self):
"""Make a copy of the config files in the Configs directory."""
self.msg("Copying config files...")
configs = glob.glob(os.path.join(
self._webwareDir, 'Configs', '*.config'))
for name in configs:
newName = os.path.join(
self._workDir, "Configs", os.path.basename(name))
if os.path.exists(newName):
self.msg(f"\t{newName} already exists.")
else:
self.msg(f"\t{newName}")
shutil.copyfile(name, newName)
def copyOtherFiles(self):
"""Make a copy of any other necessary files in the new work dir."""
self.msg("Copying other files...")
wsgiScriptFile = os.path.join('Scripts', 'WSGIScript.py')
otherFiles = ('error404.html', wsgiScriptFile)
for name in otherFiles:
newName = os.path.join(self._workDir, name)
if os.path.exists(newName):
self.msg(f"\t{newName} already exists.")
else:
oldName = os.path.join(self._webwareDir, name)
if os.path.exists(oldName):
self.msg(f"\t{newName}")
shutil.copyfile(oldName, newName)
else:
self.msg(f"\tWarning: Cannot find {oldName!r}.")
def setLibDirs(self):
"""Set the library directories in the WSGI script."""
if not self._libraryDirs:
return
self.msg("Setting the library directories...")
wsgiScript = os.path.join(self._workDir, 'Scripts', 'WSGIScript.py')
if os.path.isfile(wsgiScript):
with open(wsgiScript, encoding='utf-8') as f:
script = f.read()
if 'libDirs = []' not in script:
self.msg("\tWarning: Unexpected WSGI script")
else:
script = script.replace(
'libDirs = []', f'libDirs = {self._libraryDirs!r}')
with open(wsgiScript, 'w', encoding='utf-8') as f:
f.write(script)
else:
self.msg("\tWarning: Cannot find WSGI script.")
def makeDefaultContext(self):
"""Make a very simple context for the newbie user to play with."""
self.msg("Creating default context...")
contextDir = os.path.join(
self._workDir,
self._contextDir or self._contextName)
if contextDir.startswith(self._workDir):
configDir = contextDir[len(self._workDir):]
while configDir[:1] in (os.sep, os.altsep):
configDir = configDir[1:]
else:
configDir = contextDir
if os.path.exists(contextDir):
self.msg(f"\t{contextDir} already exists.")
else:
self.msg(f"\t{contextDir}")
os.makedirs(contextDir)
for name, source in exampleContext.items():
filename = os.path.join(contextDir, name)
if os.path.exists(filename):
self.msg(f"\t{filename} already exists.")
else:
self.msg(f"\t{filename}")
with open(filename, "w", encoding='ascii') as sourceFile:
sourceFile.write(source)
self.msg("Updating config for default context...")
filename = os.path.join(self._workDir, 'Configs', 'Application.config')
self.msg(f"\t{filename}")
with open(filename, encoding='utf-8') as configFile:
configLines = configFile.readlines()
foundContext = 0
with open(filename, 'w', encoding='utf-8') as output:
for line in configLines:
contextName = self._contextName
if line.startswith(
f"Contexts[{contextName!r}] = {configDir!r}\n"):
foundContext += 1
elif line.startswith("Contexts['default'] = "):
output.write(
f"Contexts[{contextName!r}] = {configDir!r}\n")
output.write(f"Contexts['default'] = {contextName!r}\n")
foundContext += 2
else:
output.write(line)
if foundContext < 2:
self.msg("\tWarning: Default context could not be set.")
def addGitIgnore(self):
self.msg("Creating .gitignore file...")
existed = False
ignore = '*~ *.bak *.default *.log *.patch *.pstats *.pyc *.ses *.swp'
ignore = '\n'.join(ignore.split()) + '\n\n__pycache__/\n'
ignoreDirs = 'Cache ErrorMsgs Logs Sessions'
ignore += '\n' + '\n'.join(f'/{d}/' for d in ignoreDirs.split()) + '\n'
filename = os.path.join(self._workDir, '.gitignore')
if os.path.exists(filename):
existed = True
else:
with open(filename, 'w', encoding='ascii') as f:
f.write(ignore)
if existed:
self.msg("\tDid not change existing .gitignore file.")
def changeOwner(self):
owner = {}
if self._user:
owner['user'] = self._user
if self._group:
owner['group'] = self._group
if not owner:
return
if not chown:
self.msg("\tCannot change ownership on this system.")
return
self.msg("Changing the ownership...")
mode = (
stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR |
stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP)
try:
path = self._workDir
chown(path, **owner)
chmod(path, os.stat(path).st_mode & mode)
for dirPath, dirNames, fileNames in os.walk(self._workDir):
for name in dirNames + fileNames:
path = os.path.join(dirPath, name)
chown(path, **owner)
chmod(path, os.stat(path).st_mode & mode)
except Exception as e:
self.msg("\tWarning: The ownership could not be changed.")
self.msg("\tYou may need superuser privileges to do that.")
self.msg(f"\tThe error message was: {e}")
return
mode = 0
if self._user:
mode |= stat.S_IWUSR
if self._group:
mode |= stat.S_ISGID | stat.S_IWGRP
try:
writeDirs = ('Cache', 'ErrorMsgs', 'Logs', 'Sessions')
for dirName in writeDirs:
path = os.path.join(self._workDir, dirName)
chmod(path, os.stat(path).st_mode | mode)
except Exception as e:
self.msg("\tWarning: Write permissions could not be set.")
self.msg(f"\tThe error message was: {e}")
@staticmethod
def printCompleted():
print("""
Congratulations, you've just created a runtime working directory for Webware.
To start the development server, run this command:
webware serve
If you want to open your web browser after running the server, you can
add the "-b" option. Use the "-h" option to see all other possible options.
In a productive environment, we recommend using Apache and mod_wsgi instead
of the waitress development server, and serving the static assets directly
via the Apache server. The Scripts directory contains a WSGI script that can
also be used with any other WSGI server as application server, and any other
web server as reverse proxy which can also be used to serve static assets.
Have fun!""")
def msg(self, text=None):
if self._verbose:
if text:
print(text)
else:
print()
exampleContext = { # files copied to example context
# This is used to create a very simple sample context for the new
# work dir to give the newbie something easy to play with.
'__init__.py': r"""
def contextInitialize(application, path):
# You could put initialization code here to be executed
# when the context is loaded into Webware.
pass
""",
'Main.py': r"""
from Page import Page
class Main(Page):
def title(self):
return 'My Sample Context'
def htBodyArgs(self):
return ('style="color:#202040;background-color:#e8e8f0;'
'font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;'
'font-size:12pt;line-height:1.5;padding:2em"')
def writeContent(self):
self.writeln('<h1>Welcome to Webware for Python!</h1>')
self.writeln('''
<p>
This is a sample context generated for you that has purposely been
kept very simple to give you something to play with to get yourself
started. The code that implements this page is located in <b>{}</b>.
</p>'''.format(self.request().serverSidePath()))
self.writeln('''
<p>
There are more examples and documentation in the Webware distribution,
which you can get to from here:</p>
<ul>
''')
servletPath = self.request().servletPath()
contextName = self.request().contextName()
for ctx in sorted(self.application().contexts()):
if ctx in ('default', contextName) or '/' in ctx:
continue
self.writeln(f'<li><a href="{servletPath}/{ctx}/">{ctx}</a></li>')
self.writeln('</ul>')
"""
} # end of example context files
def make(args):
workDir = args.working_directory
contextName = args.context_name
contextDir = args.context_dir
if not contextName:
if contextDir:
contextName = os.path.basename(contextDir)
else:
contextName = defaultContext
libraryDirs = args.library
if chown:
user, group = args.user, args.group
else:
user = group = None
command = MakeAppWorkDir(
workDir, contextName, contextDir, libraryDirs, user, group)
command.buildWorkDir()
def addArguments(parser):
"""Add command line arguments to the given parser."""
parser.add_argument(
'-c', '--context-name',
help='the name for the pre-installed context'
f' (by default, the name will be {defaultContext!r})')
parser.add_argument(
'-d', '--context-dir',
help='the directory where the context will be located'
' (so you can place it outside the WORK_DIR)')
parser.add_argument(
'-l', '--library', action='append',
help='other directories to be included in the search path'
' (you may specify this option multiple times)')
if chown:
parser.add_argument(
'-u', '--user',
help='the user that shall own the files'
' (name or id, e.g. user running the web server)')
parser.add_argument(
'-g', '--group',
help='the group that shall own the files'
' (name or id, e.g. group running the web server)')
parser.add_argument('working_directory', metavar='WORK_DIR')
def main(args=None):
"""Evaluate the command line arguments and call make()."""
parser = argparse.ArgumentParser(
description="Make a Webware application working directory")
addArguments(parser)
args = parser.parse_args(args)
make(args)
if __name__ == '__main__':
main()