-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink.py
204 lines (157 loc) · 5.21 KB
/
link.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
import os
import re
import requests
import tempfile
from slpp import slpp as lua
github_link = (
"https://raw.githubusercontent.com/"
"{owner}/{repo}/{branch}/{file}.lua"
)
gist_link = (
"https://gist.githubusercontent.com/"
"{owner}/{repo}/raw/{branch}/{file}.lua"
)
require_exp = r"(require\s*\(?\s*[\"'])(.+?)([\"'])"
def normalize_path(path, repo=None):
# Normalizes a require path (adds default values and shit)
if "+" in path:
schema, path = path.split("+", 1)
if schema in ("github", "gist"):
# It is a github link
branch = "master"
if "@" in path:
path, branch = path.rsplit("@", 1)
elif schema == "gist":
branch = ""
if path.count("/") == 0:
raise Exception("Invalid {} path: {}".format(schema, path))
path = path.split("/", 2)
owner, repo_name, file = path.pop(0), path.pop(0), "init"
if path:
file = path.pop(0)
return "{}+{}/{}/{}@{}".format(schema, owner, repo_name, file, branch)
elif schema == "file":
# Handle files at the end of the function
pass
else:
raise Exception("Unknown schema: {}".format(schema))
# If it doesn't have a specified schema, assume it is a file.
if repo:
# This comes from a repository, avoid local file access
if path == "config":
# Retrieve the same config file for all libarries
return "file+{}".format(path)
return "{schema}+{owner}/{repo}/{file}@{branch}".format(
file=path,
**repo
)
# Just a local file
return "file+{}".format(path)
def get_content(config, src, path):
schema, path = path.split("+", 1)
if schema in ("github", "gist"):
# Parse path
path, branch = path.rsplit("@", 1)
owner, repo_name, file = path.split("/", 2)
# Request content
link = gist_link if schema == "gist" else github_link
r = requests.get(link.format(
owner=owner, repo=repo_name, branch=branch, file=file
), stream=True)
r.raise_for_status() # Raise exception if something went wrong
# Generate temporary buffer files
tmp = tempfile._get_default_tempdir()
candidates = tempfile._get_candidate_names()
input_file = "{}/{}".format(tmp, next(candidates))
output_file = "{}/{}".format(tmp, next(candidates))
# Read stream and pipe it into the buffer
with open(input_file, "wb") as buff:
for chunk in r.iter_content(chunk_size=1024):
buff.write(chunk)
# Preprocess file
os.system(
"lua preprocess.lua --cfg {} --file {} > {}"
.format(config, input_file, output_file)
)
with open(output_file, "r") as buff:
content = buff.read()[:-1] # Remove last newline
# Delete buffer files
os.remove(input_file)
os.remove(output_file)
return content
elif schema == "file":
with open("{}/{}.lua".format(src, path), "r") as file:
return file.read()
def scan(config, files, dependencies, src, srcpath, repo=None):
# Look for require calls in the specified file
files[srcpath] = content = get_content(config, src, srcpath)
dependencies.add(srcpath)
for prefix, inp, suffix in re.findall(require_exp, content):
# Normalize and replace require() content
dep = normalize_path(inp, repo)
if dep != inp:
# Replace requirement input with the normalized version
files[srcpath] = files[srcpath].replace(
"{}{}{}".format(prefix, inp, suffix),
"{}{}{}".format(prefix, dep, suffix),
1
)
if dep not in dependencies:
schema, path = dep.split("+", 1)
if schema in ("github", "gist"):
# Github repository
path, branch = path.rsplit("@", 1)
owner, repo_name, _ = path.split("/", 2)
scan(config, files, dependencies, src, dep, {
"schema": schema,
"owner": owner, "repo": repo_name,
"branch": branch
})
elif schema == "file":
scan(config, files, dependencies, src, dep, repo)
def link(config, src, dst):
output = ["--[[ COMPUTER GENERATED FILE: DO NOT MODIFY DIRECTLY ]]--"]
# Gather files and dependencies
files, dependencies = {}, set()
scan(config, files, dependencies, src, "file+init")
# Append a require mockup, so we can use it inside the script
with open("basic-require.lua", "r") as file:
output.extend(line.rstrip() for line in file.readlines())
for name in dependencies:
print(name)
# For every dependency, we append their file and use __registerFile()
# from basic-require.lua; to be able to use it from require()
output.append(
'__registerFile("{}", {}, function()'
.format(name, len(output) + 1)
)
output.extend(files.pop(name).split("\n"))
output.append('end)')
# Add a call to run init.lua
output.extend((
'local done, result = pcall(require, "file+init")',
'if not done then',
' error(__errorMessage(result))',
'end'
))
# Remove trailing whitespace and join all lines
output = "\n".join(line.rstrip() for line in output)
# Write to output
with open(dst, "w") as file:
file.write(output)
src, dst = "./release", "./dist"
os.mkdir(dst)
# For every release created by preprocess.lua, we link the files
# ./releases/debug/* -> ./dist/debug.lua
for release in os.listdir(src):
link(
release,
"{}/{}".format(src, release),
"{}/{}.lua".format(dst, release)
)
# Read release version and show it to the current github workflow
with open("./src/release.lua", "r") as file:
info = lua.decode(file.read().replace("return ", "", 1))
print(
"::set-output name=version::v{}".format(info["version"])
)