-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
478 lines (464 loc) · 21.8 KB
/
main.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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import os
import subprocess
import tkinter
import re
from datetime import date
from tkinter import filedialog
# Main function
def main():
app_name = "Express App Generator (EXAG) - Roshane-Johnson"
app_version = "v1.4"
input_dir = input("What's the name of your project? ")
print("[!] Where should this project be stored? [Hit enter to select location]")
print(
"[!] This feature is buggy, look for the select folder dialog among your open windows and choose a directory.")
tkinter.Tk().withdraw()
gen_directory = filedialog.askdirectory()
formatted_input_dir = re.sub(" ", "_", input_dir)
project_dir: str = os.path.normpath(os.path.join(gen_directory, input_dir))
folders: list[str] = ["views", 'views/layouts', "views/partials", "public", "public/assets", "public/assets/images",
"public/assets/js", "public/assets/css", "routes", "lib"]
files: list[str] = ["app.js", ".env", ".gitignore", "tailwind.config.js", "package.json", ".prettierrc",
"views/index.ejs", "views/error.ejs",
"views/layouts/layout.ejs", "views/partials/imports.ejs", "views/partials/navbar.ejs",
"public/assets/css/_style.css", "public/assets/js/main.js",
"routes/index.js", "lib/db.js", "lib/helpers.js"]
os.mkdir(project_dir)
# Create folders
for folder in folders:
depth_1_folder: str = os.path.normpath(os.path.join(project_dir, folder))
os.mkdir(depth_1_folder)
# Create files
for file in files:
if file == ".env":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write(f'NAME={input_dir}\n'
'PORT=8080\n'
f'SESSION_SECRET=exag_{date.today().year}\n'
'\n'
'DB_HOST=localhost\n'
'DB_USER=root\n'
'DB_PASS=\n'
'DB_NAME=')
f.close()
continue
if file == ".gitignore":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('# Logs\n'
'logs\n'
'*.log\n'
'npm-debug.log*\n'
'yarn-debug.log*\n'
'yarn-error.log*\n'
'lerna-debug.log*\n'
'\n'
'# Diagnostic reports (https://nodejs.org/api/report.html)\n'
'report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n'
'\n'
'# Runtime data\n'
'pids\n'
'*.pid\n'
'*.seed\n'
'*.pid.lock\n'
'\n'
'# Directory for instrumented libs generated by jscoverage/JSCover\n'
'lib-cov\n'
'\n'
'# Coverage directory used by tools like istanbul\n'
'coverage\n'
'*.lcov\n'
'\n'
'# nyc test coverage\n'
'.nyc_output\n'
'\n'
'# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n'
'.grunt\n'
'\n'
'# Bower dependency directory (https://bower.io/)\n'
'bower_components\n'
'\n'
'# node-waf configuration\n'
'.lock-wscript\n'
'\n'
'# Compiled binary addons (https://nodejs.org/api/addons.html)\n'
'build/Release\n'
'\n'
'# Dependency directories\n'
'node_modules/\n'
'jspm_packages/\n'
'\n'
'# TypeScript v1 declaration files\n'
'typings/\n'
'\n'
'# TypeScript cache\n'
'*.tsbuildinfo\n'
'\n'
'# Optional npm cache directory\n'
'.npm\n'
'\n'
'# Optional eslint cache\n'
'.eslintcache\n'
'\n'
'# Microbundle cache\n'
'.rpt2_cache/\n'
'.rts2_cache_cjs/\n'
'.rts2_cache_es/\n'
'.rts2_cache_umd/\n'
'\n'
'# Optional REPL history\n'
'.node_repl_history\n'
'\n'
'# Output of \'npm pack\'\n'
'*.tgz\n'
'\n'
'# Yarn Integrity file\n'
'.yarn-integrity\n'
'\n'
'# dotenv environment variables file\n'
'.env\n'
'.env.test\n'
'\n'
'# parcel-bundler cache (https://parceljs.org/)\n'
'.cache\n'
'\n'
'# Next.js build output\n'
'.next\n'
'\n'
'# Nuxt.js build / generate output\n'
'.nuxt\n'
'dist\n'
'\n'
'# Gatsby files\n'
'.cache/\n'
'# Comment in the public line in if your project uses Gatsby and *not* Next.js\n'
'# https://nextjs.org/blog/next-9-1#public-directory-support\n'
'# public\n'
'\n'
'# vuepress build output\n'
'.vuepress/dist\n'
'\n'
'# Serverless directories\n'
'.serverless/\n'
'\n'
'# FuseBox cache\n'
'.fusebox/\n'
'\n'
'# DynamoDB Local files\n'
'.dynamodb/\n'
'\n'
'# TernJS port file\n'
'.tern-port\n')
f.close()
continue
if file == "package.json":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('{\n'
f' "name": "{input_dir}",\n'
' "version": "1.0.0",\n'
' "description": "Just another express application.",\n'
' "main": "app.js",\n'
' "scripts": {\n'
' "start": "node app.js",\n'
' "build": "npx tailwindcss -i ./public/assets/css/_style.css -o ./public/assets/css/style.css --watch",\n'
' "dev": "concurrently \\"nodemon app.js\\" \\"npx tailwindcss -i ./public/assets/css/_style.css -o ./public/assets/css/style.css --watch\\""\n'
' },\n'
' "keywords": [],\n'
' "author": "Roshane-Johnson",\n'
' "license": "ISC",\n'
' "type": "commonjs",\n'
' "dependencies": {\n'
' "bcrypt": "^5.0.1",\n'
' "cors": "^2.8.5",\n'
' "dotenv": "^16.0.0",\n'
' "ejs": "^3.1.7",\n'
' "express": "^4.18.1",\n'
' "express-ejs-layouts": "^2.5.1",\n'
' "express-fileupload": "^1.4.0",\n'
' "express-flash": "^0.0.2",\n'
' "express-session": "^1.17.3",\n'
' "mysql": "^2.18.1"\n'
' },\n'
' "devDependencies": {\n'
' "@tailwindcss/forms": "^0.5.2",\n'
' "@tailwindcss/typography": "^0.5.2",\n'
' "concurrently": "^7.2.1",\n'
' "nodemon": "^2.0.16",\n'
' "tailwindcss": "^3.0.24"\n'
' },\n'
' "engines": {\n'
' "node": "^16.13.2",\n'
' "npm": "^8.5.0"\n'
' }\n'
'}\n')
f.close()
continue
if file == "app.js":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('require(\'dotenv\').config()\n'
'const express = require(\'express\')\n'
'const session = require(\'express-session\')\n'
'const fileUpload = require(\'express-fileupload\')\n'
'const expressLayouts = require(\'express-ejs-layouts\')\n'
'const cors = require(\'cors\')\n'
'const path = require(\'path\')\n'
'const flash = require(\'express-flash\')\n'
'const app = express()\n'
'const PORT = process.env.PORT || 8080\n'
'const APP_NAME = process.env.NAME || \'Express App\'\n'
'\n'
'/* Express Configs */\n'
'app.set(\'view engine\', \'ejs\')\n'
'app.set(\'layout\', \'layouts/layout\')\n'
'app.set(\'views\', path.join(__dirname, \'views\'))\n'
'\n'
'/* Middlewares */\n'
'app.use(expressLayouts)\n'
'app.use(express.json())\n'
'app.use(express.urlencoded({ extended: true }))\n'
'app.use(express.static(path.join(__dirname, \'public\')))\n'
'app.use(cors([\'*\']))\n'
'app.use(flash())\n'
'app.use(fileUpload({ createParentPath: true }))\n'
'app.use(\n'
' session({\n'
' secret: process.env.SESSION_SECRET || \'secret8080\',\n'
' resave: false,\n'
' saveUninitialized: false,\n'
' cookie: {\n'
' maxAge: 1000 * 60 * 60 * 24, // day in milliseconds\n'
' },\n'
' })\n'
')\n'
'\n'
'/* View Routes */\n'
'app.use(\'/\', require(\'./routes/index\'))\n'
'\n'
'/* Start Express App */\n'
'const _app = app.listen(PORT, require(\'os\').hostname(), () => {\n'
' console.log(\n'
' `${APP_NAME} listening on http://${_app.address().address}:${_app.address().port}`\n'
' )\n'
'})\n')
f.close()
continue
if file == ".prettierrc":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('{\n'
' "trailingComma": "es5",\n'
' "arrowParens": "always",\n'
' "useTabs": true,\n'
' "tabWidth": 3,\n'
' "semi": false,\n'
' "jsxSingleQuote": false,\n'
' "singleQuote": true,\n'
' "bracketSameLine": true,\n'
' "printWidth": 90,\n'
' "bracketSpacing": true,\n'
' "htmlWhitespaceSensitivity": "css"\n'
'}\n')
f.close()
continue
if file == "routes/index.js":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('const express = require(\'express\')\n'
'const router = express.Router()\n'
'\n'
'router.get(\'/\', (req, res) => {\n'
' res.render(\'index\', { title: \'Home\' })\n'
'})\n'
'\n'
'module.exports = router\n')
f.close()
continue
if file == "views/index.ejs":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('<div class="h-screen grid place-items-center">\n'
' <h1>Express App Works</h1>\n'
'</div>\n')
f.close()
continue
if file == "views/error.ejs":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('<div class="flex items-center justify-center w-screen h-screen bg-white">\n'
' <div class="flex flex-col items-center">\n'
' <h6 class="mb-2 text-2xl font-bold text-center text-gray-800 md:text-3xl">\n'
' <span class="text-red-500">Oops!</span> <%= error.code %>\n'
' </h6>\n'
' <pre class="mb-8 text-gray-500 md:text-lg">\n'
' <%= JSON.stringify(error, undefined, 2) %>\n'
' </pre\n'
' >\n'
' <button\n'
' onclick="history.back()"\n'
' class="px-6 py-2 text-sm font-semibold uppercase text-blue-800 bg-blue-100">\n'
' Go Back\n'
' </button>\n'
' </div>\n'
'</div>\n')
f.close()
if file == "views/layouts/layout.ejs":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('<!DOCTYPE html>\n'
'<html lang="en">\n'
' <head>\n'
' <meta charset="UTF-8" />\n'
' <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n'
' <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n'
' <%- include("../partials/imports.ejs") %>\n'
' <title><%= title %> - Express App</title>\n'
' </head>\n'
' <body>\n'
' <%- include("../partials/navbar.ejs") %> <%- body %>\n'
' </body>\n'
'</html>\n')
f.close()
continue
if file == "views/partials/imports.ejs":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('<!-- JS -->\n'
'<script defer src="/assets/js/main.js"></script>\n'
'<!-- CSS -->\n'
'<link rel="stylesheet" href="/assets/css/style.css" />\n')
f.close()
continue
if file == "views/partials/navbar.ejs":
f = open(os.path.normpath(os.path.join(project_dir, file)), 'x')
f.write('<nav class="mb-10">\n'
' <div class="w-10/12 mx-auto py-5 grid grid-cols-2">\n'
' <a href="/">ExpressApp</a>\n'
' <ul class="flex justify-end">\n'
' <li><a href="/">Home</a></li>\n'
' <li><a href="/login">Login</a></li>\n'
' <li><a href="/test2">Test2</a></li>\n'
' </ul>\n'
' </div>\n'
'</nav>\n')
f.close()
continue
if file == "lib/db.js":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('const mysql = require(\'mysql\')\n'
'require(\'dotenv\').config()\n'
'\n'
'const DB = mysql.createConnection({\n'
' host: process.env.DB_HOST || \'localhost\',\n'
' port: process.env.DB_PORT || 3306,\n'
' user: process.env.DB_USER || \'root\',\n'
' password: process.env.DB_PASS || \'\',\n'
' database: process.env.DB_NAME || \'\',\n'
' dateStrings: true,\n'
' multipleStatements: true,\n'
'})\n'
'\n'
'console.log(\'Waiting for database connection...\')\n'
'DB.connect((err) => {\n'
' if (err) throw err\n'
'\n'
' console.log(\'Database Connected!\')\n'
'})\n'
'\n'
'module.exports = DB\n')
f.close()
continue
if file == "lib/helpers.js":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('/**\n'
' *\n'
' * @param {Response} res Express app response parameter\n'
' * @param {Array} data Data to return as json to the endpoint\n'
' * @param {string} message Message to return as json to the endpoint. Default: "success"\n'
' * @param {number} status HTTP Status Code to return to endpoint. Default: 200\n'
' * @returns\n'
' */\n'
'function SuccessResponse(res, data = [], message = \'success\', status = 200) {\n'
' return res.json({ message, status, data })\n'
'}\n'
'\n'
'/**\n'
' *\n'
' * @param {Response} res Express app response parameter\n'
' * @param {Array} data Data to return as json to the endpoint\n'
' * @param {string} message Message to return as json to the endpoint. Default: "error"\n'
' * @param {number} status HTTP Status Code to return to endpoint. Default: 500\n'
' * @returns\n'
' */\n'
'function ErrorResponse(res, data = [], message = \'error\', status = 500) {\n'
' return res.json({ message, status, data })\n'
'}\n'
'\n'
'/**\n'
' *\n'
' * @param {Response} res Express app response parameter\n'
' * @param {import("mysql").MysqlError} err Error to be displayed on the express error page\n'
' */\n'
'function RenderError(res, error) {\n'
' return res.render(\'error\', { error, title: \'Error\' })\n'
'}\n'
'\n'
'module.exports = { SuccessResponse, ErrorResponse, RenderError }\n')
f.close()
continue
if file == "tailwind.config.js":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('module.exports = {\n'
' content: [\'./views/**/*.ejs\'],\n'
' theme: {\n'
' extend: {},\n'
' },\n'
' plugins: [require(\'@tailwindcss/forms\'), require(\'@tailwindcss/typography\')],\n'
'}\n')
f.close()
continue
if file == "public/assets/css/_style.css":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write('@tailwind base;\n'
'@tailwind components;\n'
'@tailwind utilities;\n'
'\n'
'nav ul li {\n'
' --nav-padding: 10px;\n'
' display: flex;\n'
' padding-left: var(--nav-padding);\n'
' padding-right: var(--nav-padding);\n'
'}\n')
f.close()
continue
if file == "public/assets/js/main.js":
f = open(os.path.normpath(os.path.join(project_dir, file)), "x")
f.write(f'console.info(\'{app_name} {app_version}\')\n')
f.close()
continue
# Generation completed
completed(os.path.normpath(project_dir))
def banner():
print('\n'
'███████ ██ ██ ██████ ██████ ███████ ███████ ███████ ██████ ███████ ███ ██ \n'
'██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ \n'
'█████ ███ ██████ ██████ █████ ███████ ███████ ██ ███ █████ ██ ██ ██ \n'
'██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ \n'
'███████ ██ ██ ██ ██ ██ ███████ ███████ ███████ ██████ ███████ ██ ████ \n'
'\n')
def completed(generated_app_dir: str):
# Change generated directory to absolute path if it is in the script's directory
if "\\" not in generated_app_dir:
generated_app_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), generated_app_dir))
print()
print("*******************************************")
print("[!] Express App Generated")
print(f"[!] Directory - {generated_app_dir}")
print("*******************************************")
print()
# Open project directory after app is generated. (Windows only)
# explorer_path = os.path.join(os.getenv('WINDIR'), 'explorer.exe')
# subprocess.run([explorer_path, generated_app_dir])
# Open project directory in VSCode (If installed on Windows only)
cmd_path = os.path.join(os.getenv("WINDIR"), os.path.normpath("/Windows/System32"), "cmd.exe")
subprocess.run([cmd_path, f"cmd.exe /C cd {generated_app_dir} && code ."])
# Script entry point
if __name__ == "__main__":
try:
banner()
main()
except KeyboardInterrupt:
print("\033[93m\n\nUnexpected Exit\n\033[0m")
exit(0)