-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrump
executable file
·220 lines (165 loc) · 6.92 KB
/
rump
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
#!/usr/bin/python
# RumpKit module
import os, shutil, uuid, json, sys, errno, traceback
def run_fast_scandir(dir): # dir: str
subfolders, files = [], []
try:
for f in os.scandir(dir):
if f.is_dir():
subfolders.append(f.path)
if f.is_file():
files.append(f.path)
except FileNotFoundError:
return [], []
for dir in list(subfolders):
sf, f = run_fast_scandir(dir)
subfolders.extend(sf)
files.extend(f)
return subfolders, files
def mkdir(folder, exists_ok = True, no_del = False):
if no_del and os.path.exists(folder):
return
try:
os.system(f"rm -rvf {folder}")
except Exception as exc:
print(exc)
os.mkdir(folder)
# https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
def rreplace(s, old, new, count):
return (s[::-1].replace(old[::-1], new[::-1], count))[::-1]
# https://stackoverflow.com/questions/10840533/most-pythonic-way-to-delete-a-file-which-may-not-exist
def silentremove(filename):
try:
os.remove(filename)
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occurred
class Color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
_print = print
def print(*args, color = Color.BOLD):
_print(color + " ".join([str(x) for x in args]) + Color.END)
class RumpCommand:
def __init__(self):
self.cmds = {}
def command(self, name, *, description = None):
def wrapper_out(f):
self.cmds[name] = {"func": f, "description": description}
def wrapper():
f()
return wrapper
return wrapper_out
def help(self):
help_str = "RumpKit Help\n"
for name, cmd in self.cmds.items():
help_str += f"\n{name}: {cmd['description'] or ''}"
return help_str
def call(self):
if len(sys.argv) != 2:
print(self.help(), color=Color.BLUE)
return
try:
self.cmds[sys.argv[1]]["func"]()
except Exception as exc:
print(f"Command {sys.argv[1]} either does not exist or has error'd", color=Color.RED)
print(traceback.format_exc(), color=Color.BLUE)
rump = RumpCommand()
@rump.command("build", description="Builds the rumpkit app")
def build():
mkdir("out", exists_ok=True)
_, modules = run_fast_scandir("mods")
os.system("cp -rvf coreapi.js out/coreapi.mod.js")
for module in modules:
print("Adding module", module, "to coreapi.js")
with open("out/coreapi.mod.js") as f:
js = f.read()
with open(module) as modf:
mod = modf.read()
with open("out/coreapi.mod.js", "w") as f:
f.write(js + f"\n\n// {module}\n" + mod)
subfolders, files = run_fast_scandir("..")
files_b = files
with open("template/index.html") as f:
r = f.read()
if os.path.exists("static/ext.css"):
r = r.replace("$extstyle", """<link rel="stylesheet" href="/static/ext.css?n=$ver" />""")
else:
r = r.replace("$extstyle", "")
r = r.replace("$ver", str(uuid.uuid4()))
tmpid = uuid.uuid4()
with open(f"{tmpid}", "w") as f:
f.write(r)
cwd = os.getcwd().split("/")[-1]
print("Building in current folder:", cwd)
print("BUILD: Adding routes")
for subfolder in subfolders:
if ".git" in subfolder or "_" in subfolder or subfolder.startswith(("./template", "./bin")):
continue
if f"{subfolder}/+route" in subfolders:
print("Adding", subfolder.replace(f"../", "", 1).replace(cwd, "", 1) or "/")
parsed_subfolder = subfolder.replace(f"../", "", 1).replace(cwd, "", 1) or "/"
mkdir(f"out{parsed_subfolder}", exists_ok=True, no_del=True)
mkdir(f"out{parsed_subfolder}/+route", exists_ok=True)
mkdir(f"out{parsed_subfolder}/+data", exists_ok=True)
shutil.copy2(f"{tmpid}", f"out{parsed_subfolder}/index.html")
cp_sf = "" if parsed_subfolder == "/" else parsed_subfolder.replace("/", "", 1) + "/"
os.system(f"cp -rvf {cp_sf}+data out{parsed_subfolder}")
# Filelist generation support (for +data)
if f"{subfolder}/+route/@filelist" in files:
print("Adding", subfolder.replace(f"../", "", 1).replace(cwd, "", 1) or "/", "filelists (due to @filelist)")
_, _files = run_fast_scandir(f"{subfolder}/+data")
files = []
for f in _files:
fc = f.replace(f"{subfolder}/+data", "") or "/"
if fc == "/filelist.json":
continue
files.append(fc)
with open(f"out{parsed_subfolder}/+data/filelist.json", "w") as f:
json.dump({"files": files}, f)
try:
os.remove(f"{tmpid}")
except OSError:
pass
print("BUILD: Copying static files")
os.system("cp -rf static out")
print("BUILD: Attempting to minify .js files")
print("Minifying+optimizing coreapi.js")
os.system("google-closure-compiler --js out/coreapi.mod.js --js_output_file out/coreapi.min.js")
#os.system("rm -rf out/coreapi.mod.js")
for file in files:
if "../" + cwd not in file:
continue
_file = file.replace(f"../", "", 1).replace(cwd, "", 1).replace("/", "", 1)
if _file == "coreapi.js" or _file == "out/coreapi.mod.js":
continue
if _file.endswith(".js") and not _file.endswith(".min.js"):
print("Minifying+optimizing", _file)
os.system(f"google-closure-compiler --js {_file} --js_output_file out/{rreplace(_file, '.js', '.min.js', 1)}")
print("\n\nThe 'out' folder can be served", color=Color.BLUE)
@rump.command("clean", description="Cleanup rumpkit build")
def clean():
cwd = os.getcwd().split("/")[-1]
print("Current folder:", cwd)
os.system("rm -rvf out")
@rump.command("update", description="Update to the latest version of rumpkit")
def update():
print("Updating rumpkit...")
os.system("rm -rf rumpkit")
os.system("git clone https://github.com/Infinitybotlist/rumpkit")
print("Backing up README.md (if it exists)")
os.system("cp -f README.md README.md.bak")
os.system("cp -rf rumpkit/* .")
os.system("rm -rf README.md mkrump.sh rumpkit")
os.system("mv -f README.md.bak README.md")
print("Updating google-closure-compiler (build dependency)")
os.system("npm i -g google-closure-compiler")
rump.call()