-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy path__init__.py
674 lines (584 loc) · 20.5 KB
/
__init__.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# Helper functions for fsbuild
# This file is automatically generated by fs-package
import datetime
import json
import locale
import os
import platform
import re
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
from os import path
from typing import Dict, List, Optional
class PackageInformation:
def __init__(self):
self.values: Dict[str, str] = {}
@property
def bundleId(self) -> str:
return self.values.get(
"PACKAGE_BUNDLE_ID", self.values.get("PACKAGE_MACOS_BUNDLE_ID", "")
)
@property
def displayName(self) -> str:
"""E.g. FS-UAE Launcher."""
return self.values.get("PACKAGE_DISPLAY_NAME", self.prettyName)
@property
def name(self) -> str:
"""E.g. fs-uae-launcher."""
return self.values["PACKAGE_NAME"]
@property
def prettyName(self) -> str:
"""E.g. FS-UAE-Launcher."""
return self.values["PACKAGE_NAME_PRETTY"]
@property
def type(self):
return self.values["PACKAGE_TYPE"]
@property
def version(self):
return self.values["PACKAGE_VERSION"]
_packageInformation: Optional[PackageInformation] = None
def checkNotarizationResult(requestUuid: str):
for _ in range(60):
time.sleep(10.0)
result = run(
[
"xcrun",
"altool",
"--notarization-info",
requestUuid,
"-u",
getNotarizationUserName(),
"-p",
"@env:NOTARIZATION_PASSWORD",
"-itc_provider",
getNotarizationItcProvider(),
"--output-format",
"xml",
]
)
if "<string>success</string>" in result:
break
elif "<string>in progress</string>" in result:
print("in progress...")
continue
else:
print(result)
raise Exception("Unknown notarization result")
else:
raise Exception("Gave up notarization")
def getPackageInformation() -> PackageInformation:
global _packageInformation
if _packageInformation is None:
_packageInformation = PackageInformation()
with open("PACKAGE.FS", "r") as f:
for line in f:
try:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
value = value.strip('"')
_packageInformation.values[key] = value
except ValueError:
pass
return _packageInformation
def getAppName() -> str:
return getPackageInformation().displayName + ".app"
def getArchitecture() -> str:
machine = platform.machine()
if machine == "arm64":
arch = "ARM64"
else:
arch = "x86-64" # FIXME
return arch
def getBundleName() -> str:
packageInformation = getPackageInformation()
if packageInformation.type == "fs-library-plugin":
return getFrameworkName()
else:
return getAppName()
def getBundlePath(prefix: str = "fsbuild/_build/") -> str:
prettyName = getPackageInformation().prettyName
bundleName = getBundleName()
arch = getArchitecture()
path = f"{prefix}{prettyName}/macOS/{arch}/{bundleName}"
return path
def getDmgPath() -> str:
packageInformation = getPackageInformation()
prettyName = packageInformation.prettyName
version = packageInformation.version
arch = getArchitecture()
osDist = getOperatingSystemDist()
path = f"fsbuild/_dist/{prettyName}_{version}_{osDist}_{arch}.dmg"
return path
def getFrameworkName() -> str:
return getPackageInformation().prettyName + ".framework"
def getNotarizationItcProvider() -> str:
return os.environ.get("NOTARIZATION_PROVIDER", "")
def getNotarizationUserName() -> str:
return os.environ.get("NOTARIZATION_USERNAME", "")
def getOperatingSystemDist() -> str:
envValue = os.environ.get("SYSTEM_OS_DIST", "")
if envValue:
return envValue
elif sys.platform == "linux":
return "Linux"
elif sys.platform == "darwin":
return "macOS"
elif sys.platform == "win32":
return "Windows"
return "Unknown"
def isMacOS() -> bool:
return sys.platform == "darwin"
def notarizeApp(pathToNotarize: str, bundleId: str) -> str:
assert path.exists(pathToNotarize)
print(f"Notarizing {path.basename(pathToNotarize)}")
result = shell(
"xcrun altool --notarize-app -t osx "
"-f {pathToNotarize} "
"--primary-bundle-id {bundleId} "
"-u {appleIdUser} "
"-p @env:NOTARIZATION_PASSWORD "
"-itc_provider {itcProvider} "
"--output-format xml".format(
appleIdUser=getNotarizationUserName(),
bundleId=bundleId,
itcProvider=getNotarizationItcProvider(),
pathToNotarize=pathToNotarize,
)
)
print(result)
root = ET.fromstring(result)
dictNode = root.find("dict")
assert dictNode is not None
dictNode2 = dictNode.find("dict")
assert dictNode2 is not None
stringNode = dictNode2.find("string")
assert stringNode is not None
requestUuid = stringNode.text
assert requestUuid
print(requestUuid)
return requestUuid
def run(args: List[str]) -> str:
print(quoteArgs(args))
# p = subprocess.Popen(args, stdout = subprocess.PIPE)
# assert p.wait() == 0
# assert p.stdout
# output = p.stdout.read().decode("UTF-8")
# assert p.wait() == 0
# return output
return subprocess.check_output(args).decode("UTF-8")
def runCodeSign(args: List[str]) -> None:
# Signing sometimes fails due to Apple errors (timeouts, etc). So we try
# multiple times before giving up.
for i in range(20):
try:
shell(quoteArgs(args))
except Exception:
time.sleep(1.0 * i)
print("Attempt", i + 2)
else:
break
else:
raise Exception("Giving up signing")
def quoteArg(arg: str) -> str:
if " " in arg:
return f'"{arg}"'
return arg
def quoteArgs(args: List[str]) -> str:
return " ".join(f"{quoteArg(a)}" for a in args)
def shell(cmd: str) -> str:
print(cmd)
return subprocess.run(
cmd, shell=True, check=True, stdout=subprocess.PIPE
).stdout.decode("UTF-8")
class Version:
def __init__(self, version) -> None:
self.version = version
m = re.match("([0-9.]+[0-9])(.*)", version)
assert m is not None
parts = m.group(1).split(".")
assert 2 <= len(parts) <= 4
self.major = int(parts[0])
self.minor = int(parts[1])
self.build: Optional[int]
if len(parts) > 3:
self.build = int(parts[3])
else:
self.build = None
if len(parts) > 2:
self.revision = int(parts[2])
else:
self.revision = 0
self.tag = m.group(2)
self.commit = ""
def setLast(self, n: int) -> None:
if self.build is not None:
self.build = n
else:
self.revision = n
def __str__(self) -> str:
numbers = [self.major, self.minor, self.revision]
if self.build is not None:
numbers.append(self.build)
version = ".".join(str(x) for x in numbers)
return version + self.tag
def numCommitsSince(base: str) -> int:
to = "HEAD"
result = int(
subprocess.check_output(
["git", "rev-list", f"{base}..{to}", "--count"]
).decode()
)
return result
def findLastCommitForFile(path: str) -> str:
commit = subprocess.check_output(
["git", "log", "-n", "1", "--pretty=format:%H", "--", path]
).decode()
return commit
def findlastCommit() -> str:
commit = subprocess.check_output(
["git", "log", "-n", "1", "--pretty=format:%H"]
).decode()
return commit
def updateConfigureAc(version: Version, commit: str = "") -> None:
print("Updating configure.ac")
lines = []
with open("configure.ac", "r", encoding="UTF-8") as f:
for line in f:
if line.startswith("m4_define([fsbuild_version"):
if "_major" in line:
k = "FSBUILD_VERSION_MAJOR"
v = str(version.major)
d = "Major version"
elif "_minor" in line:
k = "FSBUILD_VERSION_MINOR"
v = str(version.minor)
d = "Minor version"
elif "_revision" in line:
k = "FSBUILD_VERSION_REVISION"
v = str(version.revision)
d = "Revision"
else:
k = "FSBUILD_VERSION"
v = str(version)
d = "Full version"
line = "m4_define([{}], [{}])\n".format(k.lower(), v)
# if line.startswith("AC_DEFINE_UNQUOTED([FSBUILD_VERSION"):
# if "_MAJOR" in line:
# k = "FSBUILD_VERSION_MAJOR"
# v = version.major
# d = "Major version"
# elif "_MINOR" in line:
# k = "FSBUILD_VERSION_MINOR"
# v = version.minor
# d = "Minor version"
# elif "_REVISION" in line:
# k = "FSBUILD_VERSION_REVISION"
# v = version.revision
# d = "Revision"
# else:
# k = "FSBUILD_VERSION"
# v = str(version)
# d = "Full version"
# line = "AC_DEFINE_UNQUOTED([{}], [{}], [{}])\n".format(k, v, d)
if line.startswith("m4_define([fsbuild_commit"):
line = "m4_define([{}], [{}])\n".format(
"fsbuild_commit", commit
)
# if line.startswith("AC_DEFINE_UNQUOTED([FSBUILD_COMMIT"):
# k = "FSBUILD_COMMIT"
# v = commit
# d = "Package commit"
# line = "AC_DEFINE_UNQUOTED([{}], [{}], [{}])\n".format(k, v, d)
lines.append(line)
with open("configure.ac", "w", encoding="UTF-8") as f:
for line in lines:
f.write(line)
def updateDebianChangelog(version: Version) -> None:
print("Updating debian/changelog")
lines = []
first_line = True
first_line_changed = False
deb_package = "unknown"
deb_version = str(version)
# deb_version = deb_version.replace("alpha", "~alpha")
# deb_version = deb_version.replace("beta", "~beta")
# deb_version = deb_version.replace("dev", "~dev")
with open("debian/changelog", "r", encoding="UTF-8") as f:
for line in f:
if first_line:
first_line = False
deb_package = line.split(" ", 1)[0]
lines.append(
"{} ({}-0) unstable; urgency=low\n".format(
deb_package, deb_version
)
)
if lines[-1] != line:
first_line_changed = True
elif line.startswith(" -- ") and first_line_changed:
# Only update date if version was changed
author, date = line.split(" ")
date = datetime.datetime.utcnow().strftime(
"%a, %d %b %Y %H:%M:%S +0000"
)
lines.append("{} {}\n".format(author, date))
else:
lines.append(line)
with open("debian/changelog", "w", encoding="UTF-8") as f:
for line in lines:
f.write(line)
def updateSpecFile(path: str, version: Version) -> None:
print("Updating", path)
lines = []
rpm_version = str(version)
# rpm_version = rpm_version.replace("alpha", "-0.1alpha")
# rpm_version = rpm_version.replace("beta", "-0.1~beta")
# rpm_version = rpm_version.replace("dev", "-0.1dev")
# if not "-" in rpm_version:
# rpm_version += "-1"
with open(path, "r", encoding="UTF-8") as f:
for line in f:
if line.startswith("%define fsbuild_version "):
lines.append(
"%define fsbuild_version {}\n".format(rpm_version)
)
# elif line.startswith("%define unmangled_version "):
# lines.append("%define unmangled_version {0}\n".format(version))
else:
lines.append(line)
with open(path, "w", newline="\n") as f:
f.write("".join(lines))
def updatePackageFs(version: Version) -> None:
print("Updating PACKAGE.FS")
lines = []
with open("PACKAGE.FS", "r", encoding="UTF-8") as f:
for line in f:
if line.startswith("PACKAGE_VERSION="):
lines.append(f"PACKAGE_VERSION={str(version)}\n")
elif line.startswith("PACKAGE_VERSION_MAJOR="):
lines.append(f"PACKAGE_VERSION_MAJOR={str(version.major)}\n")
elif line.startswith("PACKAGE_VERSION_MINOR="):
lines.append(f"PACKAGE_VERSION_MINOR={str(version.minor)}\n")
elif line.startswith("PACKAGE_VERSION_REVISION="):
lines.append(
f"PACKAGE_VERSION_REVISION={str(version.revision)}\n"
)
elif line.startswith("PACKAGE_VERSION_TAG="):
lines.append(f"PACKAGE_VERSION_TAG={str(version.tag)}\n")
elif line.startswith("PACKAGE_COMMIT="):
lines.append(f"PACKAGE_COMMIT={version.commit}\n")
else:
lines.append(line)
with open("PACKAGE.FS", "w", newline="\n") as f:
f.write("".join(lines))
def updateVersionFs(version: Version) -> None:
print("Updating VERSION.FS")
with open("VERSION.FS", "w") as f:
f.write(str(version))
f.write("\n")
def updateCommitFs(version: Version) -> None:
print("Updating COMMIT.FS")
with open("COMMIT.FS", "w") as f:
if version.commit:
f.write(version.commit)
f.write("\n")
def calculateVersion(
auto_revision: bool = False,
increment_revision: bool = False,
include_commit: bool = False,
) -> Version:
# with open("fsbuild/VERSION") as f:
with open("BASEVERSION.FS") as f:
version_str = f.read().strip()
if version_str.startswith("BASEVERSION_FS="):
version_str = version_str[len("BASEVERSION_FS=") :].strip()
# with open("PACKAGE.FS") as f:
# for line in f:
# if line.startswith("PACKAGE_VERSION="):
# version_str = line[16:].strip()
version = Version(version_str)
if auto_revision:
version_commit = findLastCommitForFile("BASEVERSION.FS")
increment = numCommitsSince(version_commit)
if increment_revision:
increment += 1
if version.build is not None:
version.build += increment
else:
version.revision += increment
if "--commit" in sys.argv:
version.commit = findlastCommit()
if True:
branch = None
githubRef = os.environ.get("GITHUB_REF")
if githubRef is not None:
if githubRef.startswith("refs/heads/"):
branch = githubRef[len("refs/heads/") :]
if githubRef.startswith("refs/pull/"):
branch = "pull" + githubRef[len("refs/pull/") :].replace(
"/", ""
)
if not branch:
branch = subprocess.check_output(
["git", "symbolic-ref", "--short", "HEAD"], encoding="UTF-8"
).strip()
if branch == "stable":
version.tag = ""
elif branch:
version.tag = f"-{branch}"
else:
raise Exception("Cannot calculate version tag from git ref")
return version
def updateVersion(version: Version) -> None:
if os.path.exists("VERSION.FS"):
updateVersionFs(version)
if os.path.exists("COMMIT.FS"):
updateCommitFs(version)
if os.path.exists("configure.ac"):
updateConfigureAc(version)
if os.path.exists("debian/changelog"):
updateDebianChangelog(version)
if os.path.exists("PACKAGE.FS"):
updatePackageFs(version)
for filename in os.listdir("."):
if filename.endswith(".spec"):
updateSpecFile(filename, version)
def versionMain() -> None:
# For date/time formatting
locale.setlocale(locale.LC_TIME, "C")
# auto_revision = "--auto" in sys.argv
auto_revision = True
increment_revision = "--next" in sys.argv
# include_commit = "--commit" in sys.argv
include_commit = True
# if "--auto-next" in sys.argv:
# auto_revision = True
# increment_revision = True
version = calculateVersion(
auto_revision=auto_revision,
increment_revision=increment_revision,
include_commit=include_commit,
)
for arg in sys.argv:
if arg.startswith("--build="):
version.build = int(arg[8:])
elif arg.startswith("--revision="):
version.revision = int(arg[11:])
elif arg.startswith("--last="):
version.setLast(int(arg[7:]))
print(str(version))
if "--print" in sys.argv:
# Only print version
pass
else:
updateVersion(version)
def buildDmg():
if not isMacOS():
print("Not building DMG on non-macOS platform")
return
dmgPath = getDmgPath()
bundlePath = getBundlePath()
packageInformation = getPackageInformation()
print(f"Building {path.basename(dmgPath)}")
if not path.exists(path.dirname(dmgPath)):
os.makedirs(path.dirname(dmgPath))
if os.path.exists(dmgPath):
os.unlink(dmgPath)
tool = "appdmg"
if tool == "appdmg":
bundlePath = getBundlePath(prefix="")
settingsPath = "fsbuild/_build/appdmg.json"
with open(settingsPath, "w", encoding="UTF-8") as f:
json.dump(
{
"title": packageInformation.displayName,
"contents": [
{
"x": 192,
"y": 344,
"type": "file",
"path": bundlePath,
},
{
"x": 448,
"y": 344,
"type": "link",
"path": "/Applications",
},
],
},
f,
)
subprocess.check_call(
[
"appdmg",
settingsPath,
dmgPath,
]
)
elif tool == "dmgbuild": # type: ignore
bundlePath = getBundlePath()
settingsPath = "fsbuild/_build/dmgbuild-settings.py"
with open(settingsPath, "w", encoding="UTF-8") as f:
f.write("format = 'UDZO'\n")
f.write("files = [\n")
f.write(f" '{bundlePath}',\n")
f.write("]\n")
f.write("symlinks = { 'Applications': '/Applications' }\n")
f.write("badge_icon = 'icon/fs-uae-launcher.icns'\n")
subprocess.check_call(
[
"dmgbuild",
"-s",
settingsPath,
"FS-UAE-Launcher",
dmgPath,
]
)
else:
raise Exception("Unknown dmg builder")
def signDmg():
if not isMacOS():
print("Not signing DMG on non-macOS platform")
return
args = [
"codesign",
"--force",
"--sign",
"Developer ID Application",
"--digest-algorithm=sha1,sha256",
]
args.append(getDmgPath())
runCodeSign(args)
def notarizeDmg():
if not isMacOS():
print("Not notarizing DMG on non-macOS platform")
return
packageInformation = getPackageInformation()
bundleId = packageInformation.bundleId
dmgPath = getDmgPath()
assert path.exists(dmgPath)
requestUuid = notarizeApp(dmgPath, bundleId)
checkNotarizationResult(requestUuid)
print('xcrun stapler staple "{}"'.format(dmgPath))
assert os.system('xcrun stapler staple "{}"'.format(dmgPath)) == 0
print("-" * 80)
print(f"[FSBUILD] Notarized {dmgPath}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Missing command")
sys.exit(1)
elif sys.argv[1] == "version":
versionMain()
elif sys.argv[1] == "build-dmg":
buildDmg()
elif sys.argv[1] == "sign-dmg":
signDmg()
elif sys.argv[1] == "notarize-dmg":
notarizeDmg()
else:
print("Unknown command")
sys.exit(1)