forked from RomanHargrave/displaycal
-
Notifications
You must be signed in to change notification settings - Fork 61
/
setup.py
executable file
·1585 lines (1334 loc) · 53.8 KB
/
setup.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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import calendar
import codecs
import glob
import os
import re
import shutil
import subprocess
import sys
import time
from configparser import RawConfigParser
from distutils.util import get_platform
from hashlib import md5, sha1
from pathlib import Path
from textwrap import fill
from time import gmtime, strftime
if sys.platform == "win32":
import msilib
pypath = Path(__file__).resolve()
pydir = pypath.parent
sys.path.insert(0, "DisplayCAL")
sys.path.insert(1, str(pydir))
def create_appdmg(zeroinstall=False):
if zeroinstall:
dmgname = name + "-0install"
srcdir = "0install"
else:
dmgname = name + "-" + version
srcdir = f"py2app.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}"
retcode = subprocess.call(
[
"hdiutil",
"create",
Path(pydir, "dist", f"{dmgname}.dmg"),
"-volname",
dmgname,
"-srcfolder",
Path(pydir, "dist", srcdir, dmgname),
]
)
if retcode != 0:
sys.exit(retcode)
def format_changelog(changelog, fmt="appstream"):
if fmt.lower() in ("appstream", "rpm"):
from xml.etree import ElementTree as ET
# Remove changelog entries of prev versions
changelog = re.sub(r'(?s:\s*<p id="changelog-.*$)', "", changelog)
# AppStream: Do not assume the format is HTML. Only paragraph (p),
# ordered list (ol) and unordered list (ul) are supported at this time.
# + list items (li)
allowed_tags = ["p", "ol", "ul", "li"]
if fmt == "rpm":
allowed_tags.append("a")
changelog = re.sub(r"\s*<dt(?:\s+[^>]*)?>.+?</dt>\n?", "", changelog)
changelog = re.sub(r"<(h4|p)(?:\s+[^>]*)?>(.+?)</\1>", r"<p>\2</p>", changelog)
# Remove everything between <!--more-->..<!--/more-->
changelog = re.sub(r"(?s:<!--more-->.+?<!--/more-->)", "", changelog)
# Remove all except allowed tags
tags = re.findall(r"<[^/][^>]+>", changelog)
for tag in tags:
tagname = tag.strip("<>").split()[0]
if tagname not in allowed_tags:
changelog = changelog.replace(tag, "")
changelog = changelog.replace("</" + tagname + ">", "")
# Remove macOS and Windows specific items
changelog = re.sub(
r"(?is:<li>[^,:<]*(?:Mac ?OS ?X?|Windows)([^,:<]*):.*?</li>)", "", changelog
)
# Remove text "Linux" in item before colon (":")
changelog = re.sub(r"(<li>[^,:<]*)\s+Linux([^,:<]*):", r"\1\2", changelog)
if fmt.lower() == "appstream":
# Conform to appstream-util validate-strict rules
def truncate(matches, maxlen):
return "%s%s%s" % (
matches.group(1),
# appstream-util validate counts bytes, not characters
matches.group(2)
.encode("UTF-8")[: maxlen - 3]
.rstrip()
.decode("UTF-8", "ignore")
+ "...",
matches.group(3),
)
# - <p> maximum is 600 chars
changelog = re.sub(
r"(<p>)\s*([^<]{601,}?)\s*(</p>)",
lambda matches: truncate(matches, 600),
changelog,
)
# - <li> cannot end in '.'
changelog = re.sub(r"([^.])\.\s*</li>", r"\1</li>", changelog)
# - <li> maximum is 100 chars
changelog = re.sub(
r"(<li>)\s*([^<]{101,}?)\s*(<(?:ol|ul|/li)>)",
lambda matches: truncate(matches, 100),
changelog,
)
# Nice formatting
changelog = re.sub(r"(?m:^\s+)", r"\t" * 4, changelog) # Multi-line
changelog = re.sub(r"(<li)", r"\t\1", changelog)
changelog = re.sub(r"\s*\n\s*\n", "\n", changelog)
# Remove line breaks
changelog = re.sub(r"\s*\n+\s*", " ", changelog)
# Parse into ETree
tree = ET.fromstring(f"<root>{changelog.encode('UTF-8')}</root>")
else:
raise ValueError(f"Changelog format not supported: {fmt!r}")
if fmt.lower() == "rpm":
changelog = ""
for lvl1 in tree:
if lvl1.tag in ("ol", "ul"):
for lvl2 in lvl1:
if lvl2.tag == "li":
changelog = f"{changelog} * {lvl2.text.lstrip()}"
links = []
link_cnt = 1
for lvl3 in lvl2:
if lvl3.tag in ("ol", "ul"):
if not changelog.endswith("\n"):
changelog = f"{changelog}\n"
for lvl4 in lvl3:
if lvl4.tag == "li":
changelog += f" {lvl4.text.lstrip()}"
for lvl5 in lvl4:
if lvl5.tag == "a":
# Collect links
links.append(lvl5.attrib["href"])
changelog = f"{changelog}{lvl5.text.strip()}[{link_cnt}]{lvl5.tail}"
link_cnt += 1
if not changelog.endswith("\n"):
changelog = f"{changelog}\n"
elif lvl3.tag == "a":
# Collect links
links.append(lvl3.attrib["href"])
changelog = f"{changelog}{lvl3.text.strip()}[{link_cnt}]{lvl3.tail}"
link_cnt += 1
if not changelog.endswith("\n"):
changelog = f"{changelog}\n"
for n, link in enumerate(links, 1):
changelog = f"{changelog} [{n}] {link}\n"
# Wrap each line to 67 chars
changelog = changelog.splitlines()
for i, line in enumerate(changelog):
block = fill(line.rstrip(), 67, subsequent_indent=" ")
changelog[i] = block
changelog = "\n".join(changelog)
else:
# Nice formatting
from xml.sax.saxutils import escape
changelog = ""
nump = 0
maxp = 3
for lvl1 in tree:
if lvl1.tag in {"p", "ol", "ul"}:
text = lvl1.text.strip()
if lvl1.tag == "p":
if nump == maxp:
continue
nump += 1
changelog = f"{changelog}\t\t\t\t<{lvl1.tag}>\n"
if text:
changelog = f"{changelog}\t\t\t\t\t{escape(text)}\n"
for lvl2 in lvl1:
if lvl2.tag == "li":
changelog = f"{changelog}\t\t\t\t\t<li>\n\t\t\t\t\t\t{escape(lvl2.text.strip())}\n"
for lvl3 in lvl2:
if lvl3.tag in {"p", "ol", "ul"}:
text = lvl3.text.strip()
if lvl3.tag == "p":
if nump == maxp:
continue
nump += 1
changelog = f"{changelog}\t\t\t\t\t\t<{lvl3.tag}>\n"
if text:
changelog = (
f"{changelog}\t\t\t\t\t\t\t{escape(text)}\n"
)
for lvl4 in lvl3:
if lvl4.tag == "li":
changelog = f"{changelog}\t\t\t\t\t\t\t<li>{escape(lvl4.text.strip())}</li>\n"
changelog = f"{changelog}\t\t\t\t\t\t</{lvl3.tag}>\n"
changelog = f"{changelog}\t\t\t\t\t</li>\n"
changelog = f"{changelog}\t\t\t\t</{lvl1.tag}>\n"
changelog = changelog.rstrip()
return changelog
def replace_placeholders(
tmpl_path: Path, out_path: Path, lastmod_time=0, iterable=None
):
global longdesc
with codecs.open(str(tmpl_path), "r", "UTF-8") as tmpl:
tmpl_data = tmpl.read()
if Path(tmpl_path).name.startswith("debian"):
longdesc_backup = longdesc
longdesc = "\n".join(
[" " + (line if line.strip() else ".") for line in longdesc.splitlines()]
)
appdatadesc = (
"\n\t\t\t"
+ longdesc.replace("\n", "\n\t\t\t").replace(".\n", ".\n\t\t</p>\n\t\t<p>\n")
+ "\n\t\t"
)
mapping = {
# e.g. Tue Jul 06 2010
"DATE": strftime(
"%a %b %d %Y", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
),
# e.g. Wed Jul 07 15:25:00 UTC 2010
"DATETIME": strftime(
"%a %b %d %H:%M:%S UTC %Y",
gmtime(lastmod_time or os.stat(tmpl_path).st_mtime),
),
"DEBPACKAGE": name.lower(),
# e.g. Wed, 07 Jul 2010 15:25:00 +0100
"DEBDATETIME": strftime(
"%a, %d %b %Y %H:%M:%S ",
gmtime(lastmod_time or os.stat(tmpl_path).st_mtime),
)
+ "+0000",
"DOMAIN": DOMAIN.lower(),
"REVERSEDOMAIN": ".".join(reversed(DOMAIN.split("."))),
"ISODATE": strftime(
"%Y-%m-%d", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
),
"ISODATETIME": strftime(
"%Y-%m-%dT%H:%M:%S", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
)
+ "+0000",
"ISOTIME": strftime(
"%H:%M", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
),
"TIMESTAMP": str(int(lastmod_time)),
"SUMMARY": description,
"LONG_DESCRIPTION": description,
"DESC": longdesc,
"APPDATADESC": f'<p>{appdatadesc}</p>\n\t\t<p xml:lang="en">{appdatadesc}</p>',
"APPNAME": name,
"APPNAME_HTML": name_html,
"APPNAME_LOWER": name.lower(),
"APPSTREAM_ID": appstream_id,
"AUTHOR": author,
"AUTHOR_EMAIL": author_email,
"MAINTAINER": author,
"MAINTAINER_EMAIL": author_email,
"MAINTAINER_EMAIL_SHA1": sha1(author_email.encode("utf-8")).hexdigest(),
"PACKAGE": name,
"PY_MAXVERSION": ".".join(str(n) for n in py_maxversion),
"PY_MINVERSION": ".".join(str(n) for n in py_minversion),
"VERSION": version,
"VERSION_SHORT": re.sub(r"(?:\.0){1,2}$", "", version),
"URL": f"https://{DOMAIN.lower()}/",
# For share counts...
"HTTPURL": f"http://{DOMAIN.lower()}/",
"WX_MINVERSION": ".".join(str(n) for n in wx_minversion),
"YEAR": strftime("%Y", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)),
}
mapping.update(iterable or {})
for key in mapping:
val = mapping[key]
tmpl_data = tmpl_data.replace(f"${{{key}}}", val)
tmpl_data = tmpl_data.replace(
f"{mapping['YEAR']}-{mapping['YEAR']}", mapping["YEAR"]
)
if Path(tmpl_path).name.startswith("debian"):
longdesc = longdesc_backup
out_path = Path(out_path)
if out_path.is_file():
with codecs.open(str(out_path), "r", "UTF-8") as out:
data = out.read()
if data == tmpl_data:
return
elif not out_path.parent.is_dir():
os.makedirs(out_path.parent)
with codecs.open(str(out_path), "w", "UTF-8") as out:
out.write(tmpl_data)
def setup():
if sys.platform == "darwin":
bdist_cmd = "py2app"
elif sys.platform == "win32":
bdist_cmd = "py2exe"
else:
bdist_cmd = "bdist_bbfreeze"
if "bdist_standalone" in sys.argv[1:]:
i = sys.argv.index("bdist_standalone")
sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
if bdist_cmd not in sys.argv[1:i]:
sys.argv.insert(i, bdist_cmd)
elif "bdist_bbfreeze" in sys.argv[1:]:
bdist_cmd = "bdist_bbfreeze"
elif "bdist_pyi" in sys.argv[1:]:
bdist_cmd = "pyi"
elif "py2app" in sys.argv[1:]:
bdist_cmd = "py2app"
elif "py2exe" in sys.argv[1:]:
bdist_cmd = "py2exe"
appdata = "appdata" in sys.argv[1:]
arch = None
bdist_appdmg = "bdist_appdmg" in sys.argv[1:]
bdist_pkg = "bdist_pkg" in sys.argv[1:]
bdist_deb = "bdist_deb" in sys.argv[1:]
bdist_pyi = "bdist_pyi" in sys.argv[1:]
buildservice = "buildservice" in sys.argv[1:]
setup_cfg = None
dry_run = "-n" in sys.argv[1:] or "--dry-run" in sys.argv[1:]
help = False
inno = "inno" in sys.argv[1:]
onefile = "-F" in sys.argv[1:] or "--onefile" in sys.argv[1:]
purge = "purge" in sys.argv[1:]
purge_dist = "purge_dist" in sys.argv[1:]
use_setuptools = "--use-setuptools" in sys.argv[1:]
zeroinstall = "0install" in sys.argv[1:]
stability = "testing"
argv = list(sys.argv[1:])
for i, arg in enumerate(reversed(argv)):
n = len(sys.argv) - i - 1
arg = arg.split("=")
if len(arg) == 2:
if arg[0] == "--force-arch":
arch = arg[1]
elif arg[0] in ("--cfg", "--stability"):
if arg[0] == "--cfg":
setup_cfg = arg[1]
else:
stability = arg[1]
sys.argv = sys.argv[:n] + sys.argv[n + 1 :]
elif arg[0] == "-h" or arg[0].startswith("--help"):
help = True
lastmod_time = 0
non_build_args = list(
filter(
lambda x: x in sys.argv[1:],
[
"bdist_appdmg",
"clean",
"purge",
"purge_dist",
"uninstall",
"-h",
"--help",
"--help-commands",
"--all",
"--name",
"--fullname",
"--author",
"--author-email",
"--maintainer",
"--maintainer-email",
"--contact",
"--contact-email",
"--url",
"--license",
"--licence",
"--description",
"--long-description",
"--platforms",
"--classifiers",
"--keywords",
"--provides",
"--requires",
"--obsoletes",
"--quiet",
"-q",
"register",
"--list-classifiers",
"upload",
"--use-distutils",
"--use-setuptools",
"--verbose",
"-v",
"finalize_msi",
],
)
)
from DisplayCAL.util_os import which
if (
Path(pydir, ".git").is_dir()
and (which("git") or which("git.exe"))
and (not sys.argv[1:] or (len(non_build_args) < len(sys.argv[1:]) and not help))
):
print("Trying to get git version information...")
git_version = None
try:
p = subprocess.Popen(
["git", "rev-parse", "--short", "HEAD"],
stdout=subprocess.PIPE,
cwd=pydir,
)
except Exception as exception:
print("...failed:", exception)
else:
git_version = p.communicate()[0].strip().decode()
version_base_file_path = Path(pydir, "VERSION_BASE")
version_base = "0.0.0".split(".")
if version_base_file_path.is_file():
with open(version_base_file_path) as version_base_file:
version_base = version_base_file.read().strip().split(".")
print("Trying to get git information...")
lastmod = ""
timestamp = None
mtime = 0
try:
p = subprocess.Popen(
["git", "log", "-1", "--format=%ct"], stdout=subprocess.PIPE, cwd=pydir
)
except Exception as exception:
print("...failed:", exception)
else:
mtime = int(p.communicate()[0].strip().decode())
timestamp = time.gmtime(mtime)
if timestamp:
lastmod = f"{strftime('%Y-%m-%dT%H:%M:%S', timestamp)}Z"
if not dry_run:
print("Generating __version__.py")
with open(Path(pydir, "DisplayCAL", "__version__.py"), "w") as versionpy:
versionpy.write("# generated by setup.py\n\n")
build_time = time.time()
versionpy.write(
f"BUILD_DATE = "
f"\"{strftime('%Y-%m-%dT%H:%M:%S', gmtime(build_time))}Z\"\n"
)
if lastmod:
versionpy.write(f"LASTMOD = {lastmod!r}\n")
if git_version:
print("Version", ".".join(version_base))
versionpy.write("VERSION = (%s)\n" % ", ".join(version_base))
versionpy.write("VERSION_BASE = (%s)\n" % ", ".join(version_base))
versionpy.write("VERSION_STRING = %r\n" % ".".join(version_base))
with open(Path(pydir, "VERSION"), "w") as versiontxt:
versiontxt.write(".".join(version_base))
backup_setup_path = Path(pydir, "setup.cfg.backup")
setup_path = Path(pydir, "setup.cfg")
if not help and not dry_run:
# Restore setup.cfg.backup if it exists
if backup_setup_path.is_file() and not setup_path.is_file():
shutil.copy2(backup_setup_path, setup_path)
if not sys.argv[1:]:
return
global name, name_html, author, author_email, description, longdesc
global DOMAIN, py_maxversion, py_minversion
global version, version_lin, version_mac
global version_src, version_tuple, version_win
global wx_minversion, appstream_id
# Do not remove the following seemingly unused variables, I know that it seems silly, but for now we need them
from DisplayCAL.meta import (
name,
name_html,
author,
author_email,
description,
lastmod,
longdesc,
DOMAIN,
py_maxversion,
py_minversion,
version,
version_lin,
version_mac,
version_src,
version_tuple,
version_win,
wx_minversion,
script2pywname,
appstream_id,
get_latest_changelog_entry,
)
longdesc = fill(longdesc)
if not lastmod_time:
lastmod_time = calendar.timegm(time.strptime(lastmod, "%Y-%m-%dT%H:%M:%SZ"))
msiversion = ".".join(
(
str(version_tuple[0]),
str(version_tuple[1]),
str(version_tuple[2]),
)
)
if not dry_run and not help:
if setup_cfg or ("bdist_msi" in sys.argv[1:] and use_setuptools):
if not backup_setup_path.exists():
shutil.copy2(setup_path, backup_setup_path)
if "bdist_msi" in sys.argv[1:] and use_setuptools:
# setuptools parses options globally even if they're not under the
# section of the currently run command
os.remove(setup_path)
if setup_cfg:
shutil.copy2(Path(pydir, "misc", f"setup.{setup_cfg}.cfg"), setup_path)
if purge or purge_dist:
# remove the "build", "DisplayCAL.egg-info" and
# "pyinstaller/bincache*" directories and their contents recursively
if dry_run:
print("dry run - nothing will be removed")
paths = []
if purge:
paths += (
glob.glob(str(Path(pydir, "build")))
+ glob.glob(str(Path(pydir, name + ".egg-info")))
+ glob.glob(str(Path(pydir, "pyinstaller", "bincache*")))
)
sys.argv.remove("purge")
if purge_dist:
paths += glob.glob(str(Path(pydir, "dist")))
sys.argv.remove("purge_dist")
for path in paths:
path = Path(path)
if path.exists():
if dry_run:
print(path)
continue
try:
shutil.rmtree(path)
except Exception as e:
print(e)
else:
print(f"Removed: {path}")
if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
return
if "readme" in sys.argv[1:]:
if not dry_run:
for tmpl_name in ["CHANGES", "README", "history"]:
for suffix in ("", "-fr"):
if suffix:
if tmpl_name == "README":
tmpl_name += suffix
else:
continue
replace_placeholders(
Path(pydir, "misc", f"{tmpl_name}.template.html"),
Path(pydir, f"{tmpl_name}.html"),
lastmod_time,
{"STABILITY": "Beta" if stability != "stable" else ""},
)
sys.argv.remove("readme")
if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
return
create_appdata = (
(appdata or "install" in sys.argv[1:] or "sdist" in sys.argv[1:])
and not help
and not dry_run
)
if (
"sdist" in sys.argv[1:]
or "install" in sys.argv[1:]
or "bdist_deb" in sys.argv[1:]
) and not help:
buildservice = True
if create_appdata or buildservice:
with codecs.open(str(Path(pydir, "CHANGES.html")), "r", "UTF-8") as f:
readme = f.read()
changelog = get_latest_changelog_entry(readme)
if create_appdata:
from DisplayCAL.setup import get_scripts
from DisplayCAL import localization as lang
scripts = get_scripts()
provides = [f"<python3>{name}</python3>"]
for script, desc in scripts:
provides.append(f"<binary>{script}</binary>")
provides = "\n\t\t".join(provides)
lang.init()
languages = []
for code, tdict in sorted(lang.ldict.items()):
if code == "en":
continue
untranslated = 0
for key in tdict:
if key.startswith("*") and key != "*":
untranslated += 1
languages.append(
'<lang percentage="%i">%s</lang>'
% (round((1 - untranslated / (len(tdict) - 1.0)) * 100), code)
)
languages = "\n\t\t".join(languages)
tmpl_name = appstream_id + ".appdata.xml"
misc_tmpl_name = Path(pydir, "misc", tmpl_name)
dist_tmpl_name = Path(pydir, "dist", tmpl_name)
replace_placeholders(
misc_tmpl_name,
dist_tmpl_name,
lastmod_time,
{
"APPDATAPROVIDES": provides,
"LANGUAGES": languages,
"CHANGELOG": format_changelog(changelog, "appstream"),
},
)
if appdata:
sys.argv.remove("appdata")
if buildservice and not dry_run:
replace_placeholders(
Path(pydir, "misc", "debian.copyright"),
Path(pydir, "dist", "copyright"),
lastmod_time,
)
if "buildservice" in sys.argv[1:]:
sys.argv.remove("buildservice")
if bdist_deb:
bdist_args = ["bdist_rpm"]
if not arch:
arch = get_platform().split("-")[1]
bdist_args += ["--force-arch=" + arch]
i = sys.argv.index("bdist_deb")
sys.argv = sys.argv[:i] + bdist_args + sys.argv[i + 1 :]
if bdist_pyi:
i = sys.argv.index("bdist_pyi")
sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
if "-F" in sys.argv[1:]:
sys.argv.remove("-F")
if "--onefile" in sys.argv[1:]:
sys.argv.remove("--onefile")
if inno and sys.platform == "win32":
tmpl_types = ["pyi" if bdist_pyi else bdist_cmd]
if zeroinstall:
tmpl_types.extend(["0install", "0install-per-user"])
for tmpl_type in tmpl_types:
inno_template_path = Path(pydir, "misc", f"{name}-Setup-{tmpl_type}.iss")
with open(inno_template_path, "r") as inno_template:
print(f"inno_template_path: {inno_template_path}")
template = inno_template.read()
# print(template)
inno_script = template % {
"AppCopyright": f"© {strftime('%Y')} {author}",
"AppName": name,
"AppVerName": version,
"AppPublisher": author,
"AppPublisherURL": f"https://{DOMAIN}/",
"AppSupportURL": f"https://{DOMAIN}/",
"AppUpdatesURL": f"https://{DOMAIN}/",
"VersionInfoVersion": ".".join(map(str, version_tuple)),
"VersionInfoTextVersion": version,
"AppVersion": version,
"Platform": get_platform(),
"PythonVersion": f"{sys.version_info[0]}.{sys.version_info[1]}",
"URL": f"https://{DOMAIN}/",
"HTTPURL": f"http://{DOMAIN}/",
}
inno_path = Path(
"dist",
inno_template_path.name.replace(
bdist_cmd,
f"{bdist_cmd}.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}",
),
)
if not dry_run:
dist_path = Path("dist")
if not dist_path.exists():
os.makedirs(dist_path)
with open(inno_path, "wb") as inno_file:
inno_file.write(inno_script.encode("MBCS", "replace"))
sys.argv.remove("inno")
if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
return
if "finalize_msi" in sys.argv[1:]:
db = msilib.OpenDatabase(
rf"dist\{name}-{msiversion}.win32-py{sys.version_info[0]}.{sys.version_info[1]}.msi",
msilib.MSIDBOPEN_TRANSACT,
)
view = db.OpenView("SELECT Value FROM Property WHERE Property = 'ProductCode'")
view.Execute(None)
record = view.Fetch()
productcode = record.GetString(1)
view.Close()
msilib.add_data(
db,
"Directory",
[("ProgramMenuFolder", "TARGETDIR", ".")], # Directory # Parent
) # DefaultDir
msilib.add_data(
db,
"Directory",
[
(
"MenuDir", # Directory
"ProgramMenuFolder", # Parent
name.upper()[:6] + "~1|" + name,
)
],
) # DefaultDir
msilib.add_data(
db,
"Icon",
[
(
name + ".ico", # Name
msilib.Binary(
str(Path(pydir, name, "theme", "icons", name + ".ico"))
),
)
],
) # Data
msilib.add_data(
db,
"Icon",
[
(
"uninstall.ico", # Name
msilib.Binary(
str(
Path(pydir, name, "theme", "icons", name + "-uninstall.ico")
)
),
)
],
) # Data
msilib.add_data(
db,
"RemoveFile",
[
(
"MenuDir", # FileKey
name, # Component
None, # FileName
"MenuDir", # DirProperty
2,
)
],
) # InstallMode
msilib.add_data(
db,
"Registry",
[
(
"DisplayIcon", # Registry
-1, # Root
rf"Software\Microsoft\Windows\CurrentVersion\Uninstall\{productcode}",
"DisplayIcon", # Name
r"[icons]%s.ico" % name, # Value
name,
)
],
) # Component
msilib.add_data(
db,
"Shortcut",
[
(
name, # Shortcut
"MenuDir", # Directory
name.upper()[:6] + "~1|" + name, # Name
name, # Component
r"[TARGETDIR]pythonw.exe", # Target
rf'"[TARGETDIR]Scripts\{name}"', # Arguments
None, # Description
None, # Hotkey
f"{name}.ico", # Icon
None, # IconIndex
None, # ShowCmd
name,
)
],
) # WkDir
msilib.add_data(
db,
"Shortcut",
[
(
"CHANGES", # Shortcut
"MenuDir", # Directory
"CHANGES|CHANGES", # Name
name, # Component
rf"[{name}]CHANGES.html", # Target
None, # Arguments
None, # Description
None, # Hotkey
None, # Icon
None, # IconIndex
None, # ShowCmd
name,
)
],
) # WkDir
msilib.add_data(
db,
"Shortcut",
[
(
"LICENSE", # Shortcut
"MenuDir", # Directory
"LICENSE|LICENSE", # Name
name, # Component
rf"[{name}]LICENSE.txt", # Target
None, # Arguments
None, # Description
None, # Hotkey
None, # Icon
None, # IconIndex
None, # ShowCmd
name,
)
],
) # WkDir
msilib.add_data(
db,
"Shortcut",
[
(
"README", # Shortcut
"MenuDir", # Directory
"README|README", # Name
name, # Component
rf"[{name}]README.html", # Target
None, # Arguments
None, # Description
None, # Hotkey
None, # Icon
None, # IconIndex
None, # ShowCmd
name,
)
],
) # WkDir
msilib.add_data(
db,
"Shortcut",
[
(
"Uninstall", # Shortcut
"MenuDir", # Directory
"UNINST|Uninstall", # Name
name, # Component
r"[SystemFolder]msiexec", # Target
r"/x" + productcode, # Arguments
None, # Description
None, # Hotkey
"uninstall.ico", # Icon
None, # IconIndex
None, # ShowCmd
"SystemFolder",
)
],
) # WkDir
if not dry_run:
db.Commit()
sys.argv.remove("finalize_msi")
if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
return
if zeroinstall:
sys.argv.remove("0install")
if bdist_appdmg:
sys.argv.remove("bdist_appdmg")
if bdist_pkg:
sys.argv.remove("bdist_pkg")
if (
not zeroinstall
and not buildservice
and not appdata
and not bdist_appdmg
and not bdist_pkg
) or sys.argv[1:]:
print(sys.argv[1:])
from DisplayCAL.setup import setup
setup()
if dry_run or help:
return
if buildservice:
# Create control files