forked from apernet/hysteria
-
Notifications
You must be signed in to change notification settings - Fork 63
/
hyperbole.py
executable file
·513 lines (424 loc) · 14.1 KB
/
hyperbole.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import re
import sys
import subprocess
import datetime
import shutil
# Hyperbole is the official build script for Hysteria.
# Available environment variables for controlling the build:
# - HY_APP_VERSION: App version
# - HY_APP_COMMIT: App commit hash
# - HY_APP_PLATFORMS: Platforms to build for (e.g. "windows/amd64,linux/arm")
LOGO = """
░█░█░█░█░█▀█░█▀▀░█▀▄░█▀▄░█▀█░█░░░█▀▀
░█▀█░░█░░█▀▀░█▀▀░█▀▄░█▀▄░█░█░█░░░█▀▀
░▀░▀░░▀░░▀░░░▀▀▀░▀░▀░▀▀░░▀▀▀░▀▀▀░▀▀▀
"""
DESC = "Hyperbole is the official build script for Hysteria."
BUILD_DIR = "build"
CORE_SRC_DIR = "./core"
EXTRAS_SRC_DIR = "./extras"
APP_SRC_DIR = "./app"
APP_SRC_CMD_PKG = "github.com/apernet/hysteria/app/v2/cmd"
MODULE_SRC_DIRS = [CORE_SRC_DIR, EXTRAS_SRC_DIR, APP_SRC_DIR]
ARCH_ALIASES = {
"arm": {
"GOARCH": "arm",
"GOARM": "7",
},
"armv5": {
"GOARCH": "arm",
"GOARM": "5",
},
"armv6": {
"GOARCH": "arm",
"GOARM": "6",
},
"armv7": {
"GOARCH": "arm",
"GOARM": "7",
},
"mips": {
"GOARCH": "mips",
"GOMIPS": "",
},
"mipsle": {
"GOARCH": "mipsle",
"GOMIPS": "",
},
"mips-sf": {
"GOARCH": "mips",
"GOMIPS": "softfloat",
},
"mipsle-sf": {
"GOARCH": "mipsle",
"GOMIPS": "softfloat",
},
"amd64": {
"GOARCH": "amd64",
"GOAMD64": "",
},
"amd64-avx": {
"GOARCH": "amd64",
"GOAMD64": "v3",
},
}
def check_command(args):
try:
subprocess.check_call(
args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
return True
except Exception:
return False
def check_build_env():
if not check_command(["git", "--version"]):
print("Git is not installed. Please install Git and try again.")
return False
if not check_command(["git", "rev-parse", "--is-inside-work-tree"]):
print("Not in a Git repository. Please go to the project root and try again.")
return False
if not check_command(["go", "version"]):
print("Go is not installed. Please install Go and try again.")
return False
return True
def get_app_version():
app_version = os.environ.get("HY_APP_VERSION")
if not app_version:
try:
output = (
subprocess.check_output(
["git", "describe", "--tags", "--always", "--match", "app/v*"]
)
.decode()
.strip()
)
app_version = output.split("/")[-1]
except Exception:
app_version = "Unknown"
return app_version
def get_app_version_code(str=None):
if not str:
str = get_app_version()
match = re.search(r"v(\d+)\.(\d+)\.(\d+)", str)
if match:
major, minor, patch = match.groups()
major = major.zfill(2)[:2]
minor = minor.zfill(2)[:2]
patch = patch.zfill(2)[:2]
return int(f"{major}{minor}{patch[:2]}")
else:
return 0
def get_app_commit():
app_commit = os.environ.get("HY_APP_COMMIT")
if not app_commit:
try:
app_commit = (
subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()
)
except Exception:
app_commit = "Unknown"
return app_commit
def get_current_os_arch():
d_os = subprocess.check_output(["go", "env", "GOOS"]).decode().strip()
d_arch = subprocess.check_output(["go", "env", "GOARCH"]).decode().strip()
return (d_os, d_arch)
def get_app_platforms():
platforms = os.environ.get("HY_APP_PLATFORMS")
if not platforms:
d_os, d_arch = get_current_os_arch()
return [(d_os, d_arch)]
result = []
for platform in platforms.split(","):
platform = platform.strip()
if not platform:
continue
parts = platform.split("/")
if len(parts) != 2:
continue
result.append((parts[0], parts[1]))
return result
def cmd_build(pprof=False, release=False, race=False):
if not check_build_env():
return
os.makedirs(BUILD_DIR, exist_ok=True)
app_version = get_app_version()
app_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
app_commit = get_app_commit()
ldflags = [
"-X",
APP_SRC_CMD_PKG + ".appVersion=" + app_version,
"-X",
APP_SRC_CMD_PKG + ".appDate=" + app_date,
"-X",
APP_SRC_CMD_PKG
+ ".appType="
+ ("release" if release else "dev")
+ ("-pprof" if pprof else ""),
"-X",
APP_SRC_CMD_PKG + ".appCommit=" + app_commit,
]
if release:
ldflags.append("-s")
ldflags.append("-w")
for os_name, arch in get_app_platforms():
print("Building for %s/%s..." % (os_name, arch))
out_name = "hysteria-%s-%s" % (os_name, arch)
if os_name == "windows":
out_name += ".exe"
env = os.environ.copy()
env["GOOS"] = os_name
if arch in ARCH_ALIASES:
for k, v in ARCH_ALIASES[arch].items():
env[k] = v
else:
env["GOARCH"] = arch
if os_name == "android":
env["CGO_ENABLED"] = "1"
ANDROID_NDK_HOME = (
os.environ.get("ANDROID_NDK_HOME")
+ "/toolchains/llvm/prebuilt/linux-x86_64/bin"
)
if arch == "arm64":
env["CC"] = ANDROID_NDK_HOME + "/aarch64-linux-android29-clang"
elif arch == "armv7":
env["CC"] = ANDROID_NDK_HOME + "/armv7a-linux-androideabi29-clang"
elif arch == "386":
env["CC"] = ANDROID_NDK_HOME + "/i686-linux-android29-clang"
elif arch == "amd64":
env["CC"] = ANDROID_NDK_HOME + "/x86_64-linux-android29-clang"
else:
print("Unsupported arch for android: %s" % arch)
return
else:
env["CGO_ENABLED"] = "1" if race else "0" # Race detector requires cgo
plat_ldflags = ldflags.copy()
plat_ldflags.append("-X")
plat_ldflags.append(APP_SRC_CMD_PKG + ".appPlatform=" + os_name)
plat_ldflags.append("-X")
plat_ldflags.append(APP_SRC_CMD_PKG + ".appArch=" + arch)
cmd = [
"go",
"build",
"-o",
os.path.join(BUILD_DIR, out_name),
"-ldflags",
" ".join(plat_ldflags),
]
if pprof:
cmd.append("-tags")
cmd.append("pprof")
if race:
cmd.append("-race")
if release:
cmd.append("-trimpath")
cmd.append(APP_SRC_DIR)
try:
subprocess.check_call(cmd, env=env)
except Exception:
print("Failed to build for %s/%s" % (os_name, arch))
sys.exit(1)
print("Built %s" % out_name)
def cmd_run(args, pprof=False, race=False):
if not check_build_env():
return
app_version = get_app_version()
app_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
app_commit = get_app_commit()
current_os, current_arch = get_current_os_arch()
ldflags = [
"-X",
APP_SRC_CMD_PKG + ".appVersion=" + app_version,
"-X",
APP_SRC_CMD_PKG + ".appDate=" + app_date,
"-X",
APP_SRC_CMD_PKG + ".appType=dev-run",
"-X",
APP_SRC_CMD_PKG + ".appCommit=" + app_commit,
"-X",
APP_SRC_CMD_PKG + ".appPlatform=" + current_os,
"-X",
APP_SRC_CMD_PKG + ".appArch=" + current_arch,
]
cmd = ["go", "run", "-ldflags", " ".join(ldflags)]
if pprof:
cmd.append("-tags")
cmd.append("pprof")
if race:
cmd.append("-race")
cmd.append(APP_SRC_DIR)
cmd.extend(args)
try:
subprocess.check_call(cmd)
except KeyboardInterrupt:
pass
except subprocess.CalledProcessError as e:
# Pass through the exit code
sys.exit(e.returncode)
def cmd_format():
if not check_command(["gofumpt", "-version"]):
print("gofumpt is not installed. Please install gofumpt and try again.")
return
try:
subprocess.check_call(["gofumpt", "-w", "-l", "-extra", "."])
except Exception:
print("Failed to format code")
def cmd_mockgen():
if not check_command(["mockery", "--version"]):
print("mockery is not installed. Please install mockery and try again.")
return
for dirpath, dirnames, filenames in os.walk("."):
dirnames[:] = [d for d in dirnames if not d.startswith(".")]
if ".mockery.yaml" in filenames:
print("Generating mocks for %s..." % dirpath)
try:
subprocess.check_call(["mockery"], cwd=dirpath)
except Exception:
print("Failed to generate mocks for %s" % dirpath)
def cmd_protogen():
if not check_command(["protoc", "--version"]):
print("protoc is not installed. Please install protoc and try again.")
return
for dirpath, dirnames, filenames in os.walk("."):
dirnames[:] = [d for d in dirnames if not d.startswith(".")]
proto_files = [f for f in filenames if f.endswith(".proto")]
if len(proto_files) > 0:
for proto_file in proto_files:
print("Generating protobuf for %s..." % proto_file)
try:
subprocess.check_call(
["protoc", "--go_out=paths=source_relative:.", proto_file],
cwd=dirpath,
)
except Exception:
print("Failed to generate protobuf for %s" % proto_file)
def cmd_tidy():
if not check_build_env():
return
for dir in MODULE_SRC_DIRS:
print("Tidying %s..." % dir)
try:
subprocess.check_call(["go", "mod", "tidy"], cwd=dir)
except Exception:
print("Failed to tidy %s" % dir)
print("Syncing go work...")
try:
subprocess.check_call(["go", "work", "sync"])
except Exception:
print("Failed to sync go work")
def cmd_test(module=None):
if not check_build_env():
return
if module:
print("Testing %s..." % module)
try:
subprocess.check_call(["go", "test", "-v", "./..."], cwd=module)
except Exception:
print("Failed to test %s" % module)
else:
for dir in MODULE_SRC_DIRS:
print("Testing %s..." % dir)
try:
subprocess.check_call(["go", "test", "-v", "./..."], cwd=dir)
except Exception:
print("Failed to test %s" % dir)
def cmd_publish(urgent=False):
import requests
if not check_build_env():
return
app_version = get_app_version()
app_version_code = get_app_version_code(app_version)
if app_version_code == 0:
print("Invalid app version")
return
payload = {
"code": app_version_code,
"ver": app_version,
"chan": "release",
"url": "https://github.com/apernet/hysteria/releases",
"urgent": urgent,
}
headers = {
"Content-Type": "application/json",
"Authorization": os.environ.get("HY_API_POST_KEY"),
}
resp = requests.post("https://api.hy2.io/v1/update", json=payload, headers=headers)
if resp.status_code == 200:
print("Published %s" % app_version)
else:
print("Failed to publish %s, status code: %d" % (app_version, resp.status_code))
def cmd_clean():
shutil.rmtree(BUILD_DIR, ignore_errors=True)
def cmd_about():
print(LOGO)
print(DESC)
def main():
parser = argparse.ArgumentParser()
p_cmd = parser.add_subparsers(dest="command")
p_cmd.required = True
# Run
p_run = p_cmd.add_parser("run", help="Run the app")
p_run.add_argument(
"-p", "--pprof", action="store_true", help="Run with pprof enabled"
)
p_run.add_argument(
"-d", "--race", action="store_true", help="Build with data race detection"
)
p_run.add_argument("args", nargs=argparse.REMAINDER)
# Build
p_build = p_cmd.add_parser("build", help="Build the app")
p_build.add_argument(
"-p", "--pprof", action="store_true", help="Build with pprof enabled"
)
p_build.add_argument(
"-r", "--release", action="store_true", help="Build a release version"
)
p_build.add_argument(
"-d", "--race", action="store_true", help="Build with data race detection"
)
# Format
p_cmd.add_parser("format", help="Format the code")
# Mockgen
p_cmd.add_parser("mockgen", help="Generate mock interfaces")
# Protogen
p_cmd.add_parser("protogen", help="Generate protobuf interfaces")
# Tidy
p_cmd.add_parser("tidy", help="Tidy the go modules")
# Test
p_test = p_cmd.add_parser("test", help="Test the code")
p_test.add_argument("module", nargs="?", help="Module to test")
# Publish
p_pub = p_cmd.add_parser("publish", help="Publish the current version")
p_pub.add_argument(
"-u", "--urgent", action="store_true", help="Publish as an urgent update"
)
# Clean
p_cmd.add_parser("clean", help="Clean the build directory")
# About
p_cmd.add_parser("about", help="Print about information")
args = parser.parse_args()
if args.command == "run":
cmd_run(args.args, args.pprof, args.race)
elif args.command == "build":
cmd_build(args.pprof, args.release, args.race)
elif args.command == "format":
cmd_format()
elif args.command == "mockgen":
cmd_mockgen()
elif args.command == "protogen":
cmd_protogen()
elif args.command == "tidy":
cmd_tidy()
elif args.command == "test":
cmd_test(args.module)
elif args.command == "publish":
cmd_publish(args.urgent)
elif args.command == "clean":
cmd_clean()
elif args.command == "about":
cmd_about()
if __name__ == "__main__":
main()