Debian Codegraph @

setup.py

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env python3
2
3 import codecs
4 import glob
5 import os
6 import re
7 import shutil
8 import subprocess
9 import sys
10 import time
11 from configparser import RawConfigParser
12 from distutils.util import get_platform
13 from hashlib import md5, sha1
14 from pathlib import Path
15 from textwrap import fill
16 from time import gmtime, strftime
17
18 if sys.platform == "win32":
19 try:
20 import msilib
21 except ModuleNotFoundError:
22 msilib = None
23
24
25 pypath = Path(__file__).resolve()
26 pydir = pypath.parent
27
28 sys.path.insert(0, "DisplayCAL")
29 sys.path.insert(1, str(pydir))
30
31
32 def generate_version_file() -> None:
33 """Generate VERSION file from DisplayCAL/VERSION if it exists.
34
35 otherwise use "0.0.0" as version.
36 """
37 version_base_file_path = Path(pydir, "DisplayCAL", "VERSION")
38 version_base = "0.0.0"
39
40 if version_base_file_path.is_file():
41 with open(version_base_file_path) as version_base_file:
42 version_base = version_base_file.read().strip()
43
44 with open(Path(pydir, "VERSION"), "w") as versiontxt:
45 versiontxt.write(version_base)
46
47
48 def create_appdmg(zeroinstall=False):
49 from DisplayCAL.meta import NAME, VERSION_STRING
50 if zeroinstall:
51 dmgname = f"{NAME}-0install"
52 srcdir = "0install"
53 else:
54 dmgname = f"{NAME}-{VERSION_STRING}"
55 srcdir = f"py2app.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}"
56
57 retcode = subprocess.call(
58 [
59 "hdiutil",
60 "create",
61 Path(pydir, "dist", f"{dmgname}.dmg"),
62 "-volname",
63 dmgname,
64 "-srcfolder",
65 Path(pydir, "dist", srcdir, dmgname),
66 ]
67 )
68
69 if retcode != 0:
70 sys.exit(retcode)
71
72
73 def format_changelog(changelog, fmt="appstream"):
74 if fmt.lower() in ("appstream", "rpm"):
75 from xml.etree import ElementTree as ET
76
77 # Remove changelog entries of prev versions
78 changelog = re.sub(r'(?s:\s*<p id="changelog-.*$)', "", changelog)
79 # AppStream: Do not assume the format is HTML. Only paragraph (p),
80 # ordered list (ol) and unordered list (ul) are supported at this time.
81 # + list items (li)
82 allowed_tags = ["p", "ol", "ul", "li"]
83
84 if fmt == "rpm":
85 allowed_tags.append("a")
86
87 changelog = re.sub(r"\s*<dt(?:\s+[^>]*)?>.+?</dt>\n?", "", changelog)
88 changelog = re.sub(r"<(h4|p)(?:\s+[^>]*)?>(.+?)</\1>", r"<p>\2</p>", changelog)
89 # Remove everything between <!--more-->..<!--/more-->
90 changelog = re.sub(r"(?s:<!--more-->.+?<!--/more-->)", "", changelog)
91 # Remove all except allowed tags
92 tags = re.findall(r"<[^/][^>]+>", changelog)
93
94 for tag in tags:
95 tagname = tag.strip("<>").split()[0]
96
97 if tagname not in allowed_tags:
98 changelog = changelog.replace(tag, "")
99 changelog = changelog.replace("</" + tagname + ">", "")
100
101 # Remove macOS and Windows specific items
102 changelog = re.sub(
103 r"(?is:<li>[^,:<]*(?:Mac ?OS ?X?|Windows)([^,:<]*):.*?</li>)", "", changelog
104 )
105 # Remove text "Linux" in item before colon (":")
106 changelog = re.sub(r"(<li>[^,:<]*)\s+Linux([^,:<]*):", r"\1\2", changelog)
107
108 if fmt.lower() == "appstream":
109 # Conform to appstream-util validate-strict rules
110 def truncate(matches, maxlen):
111 return "%s%s%s" % (
112 matches.group(1),
113 # appstream-util validate counts bytes, not characters
114 matches.group(2)
115 .encode("UTF-8")[: maxlen - 3]
116 .rstrip()
117 .decode("UTF-8", "ignore")
118 + "...",
119 matches.group(3),
120 )
121
122 # - <p> maximum is 600 chars
123 changelog = re.sub(
124 r"(<p>)\s*([^<]{601,}?)\s*(</p>)",
125 lambda matches: truncate(matches, 600),
126 changelog,
127 )
128 # - <li> cannot end in '.'
129 changelog = re.sub(r"([^.])\.\s*</li>", r"\1</li>", changelog)
130 # - <li> maximum is 100 chars
131 changelog = re.sub(
132 r"(<li>)\s*([^<]{101,}?)\s*(<(?:ol|ul|/li)>)",
133 lambda matches: truncate(matches, 100),
134 changelog,
135 )
136
137 # Nice formatting
138 changelog = re.sub(r"(?m:^\s+)", r"\t" * 4, changelog) # Multi-line
139 changelog = re.sub(r"(<li)", r"\t\1", changelog)
140 changelog = re.sub(r"\s*\n\s*\n", "\n", changelog)
141 # Remove line breaks
142 changelog = re.sub(r"\s*\n+\s*", " ", changelog)
143
144 # Parse into ETree
145 tree = ET.fromstring(f"<root>{changelog.encode('UTF-8')}</root>")
146 else:
147 raise ValueError(f"Changelog format not supported: {fmt!r}")
148
149 if fmt.lower() == "rpm":
150 changelog = ""
151
152 for lvl1 in tree:
153 if lvl1.tag not in ("ol", "ul"):
154 continue
155 for lvl2 in lvl1:
156 if lvl2.tag != "li":
157 continue
158 changelog = f"{changelog} * {lvl2.text.lstrip()}"
159 links = []
160 link_cnt = 1
161
162 for lvl3 in lvl2:
163 if lvl3.tag in ("ol", "ul"):
164 if not changelog.endswith("\n"):
165 changelog = f"{changelog}\n"
166
167 for lvl4 in lvl3:
168 if lvl4.tag == "li":
169 changelog += f" {lvl4.text.lstrip()}"
170
171 for lvl5 in lvl4:
172 if lvl5.tag == "a":
173 # Collect links
174 links.append(lvl5.attrib["href"])
175 changelog = f"{changelog}{lvl5.text.strip()}[{link_cnt}]{lvl5.tail}"
176 link_cnt += 1
177
178 if not changelog.endswith("\n"):
179 changelog = f"{changelog}\n"
180 elif lvl3.tag == "a":
181 # Collect links
182 links.append(lvl3.attrib["href"])
183 changelog = f"{changelog}{lvl3.text.strip()}[{link_cnt}]{lvl3.tail}"
184 link_cnt += 1
185
186 if not changelog.endswith("\n"):
187 changelog = f"{changelog}\n"
188
189 for n, link in enumerate(links, 1):
190 changelog = f"{changelog} [{n}] {link}\n"
191
192 # Wrap each line to 67 chars
193 changelog = changelog.splitlines()
194
195 for i, line in enumerate(changelog):
196 block = fill(line.rstrip(), 67, subsequent_indent=" ")
197 changelog[i] = block
198
199 changelog = "\n".join(changelog)
200 else:
201 # Nice formatting
202 from xml.sax.saxutils import escape
203
204 changelog = ""
205 nump = 0
206 maxp = 3
207
208 for lvl1 in tree:
209 if lvl1.tag in {"p", "ol", "ul"}:
210 text = lvl1.text.strip()
211
212 if lvl1.tag == "p":
213 if nump == maxp:
214 continue
215 nump += 1
216
217 changelog = f"{changelog}\t\t\t\t<{lvl1.tag}>\n"
218
219 if text:
220 changelog = f"{changelog}\t\t\t\t\t{escape(text)}\n"
221
222 for lvl2 in lvl1:
223 if lvl2.tag != "li":
224 continue
225 changelog = f"{changelog}\t\t\t\t\t<li>\n\t\t\t\t\t\t{escape(lvl2.text.strip())}\n"
226
227 for lvl3 in lvl2:
228 if lvl3.tag in {"p", "ol", "ul"}:
229 text = lvl3.text.strip()
230
231 if lvl3.tag == "p":
232 if nump == maxp:
233 continue
234 nump += 1
235
236 changelog = f"{changelog}\t\t\t\t\t\t<{lvl3.tag}>\n"
237
238 if text:
239 changelog = (
240 f"{changelog}\t\t\t\t\t\t\t{escape(text)}\n"
241 )
242
243 for lvl4 in lvl3:
244 if lvl4.tag == "li":
245 changelog = f"{changelog}\t\t\t\t\t\t\t<li>{escape(lvl4.text.strip())}</li>\n"
246
247 changelog = f"{changelog}\t\t\t\t\t\t</{lvl3.tag}>\n"
248 changelog = f"{changelog}\t\t\t\t\t</li>\n"
249 changelog = f"{changelog}\t\t\t\t</{lvl1.tag}>\n"
250 changelog = changelog.rstrip()
251
252 return changelog
253
254
255 def replace_placeholders(
256 tmpl_path: Path, out_path: Path, lastmod_time= 0, iterable=None
257 ):
258 global LONG_DESCRIPTION
259 import DisplayCAL
260
261 with open(str(tmpl_path), "r", encoding="UTF-8") as tmpl:
262 tmpl_data = tmpl.read()
263
264 if Path(tmpl_path).name.startswith("debian"):
265 longdesc_backup = LONG_DESCRIPTION
266 LONG_DESCRIPTION = "\n".join(
267 [" " + (line if line.strip() else ".") for line in LONG_DESCRIPTION.splitlines()]
268 )
269
270 appdatadesc = (
271 "\n\t\t\t"
272 + LONG_DESCRIPTION.replace("\n", "\n\t\t\t").replace(".\n", ".\n\t\t</p>\n\t\t<p>\n")
273 + "\n\t\t"
274 )
275 mapping = {
276 # e.g. Tue Jul 06 2010
277 "DATE": strftime(
278 "%a %b %d %Y", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
279 ),
280 # e.g. Wed Jul 07 15:25:00 UTC 2010
281 "DATETIME": strftime(
282 "%a %b %d %H:%M:%S UTC %Y",
283 gmtime(lastmod_time or os.stat(tmpl_path).st_mtime),
284 ),
285 "DEBPACKAGE": NAME.lower(),
286 # e.g. Wed, 07 Jul 2010 15:25:00 +0100
287 "DEBDATETIME": strftime(
288 "%a, %d %b %Y %H:%M:%S ",
289 gmtime(lastmod_time or os.stat(tmpl_path).st_mtime),
290 )
291 + "+0000",
292 "DOMAIN": DOMAIN.lower(),
293 "REVERSEDOMAIN": ".".join(reversed(DOMAIN.split("."))),
294 "ISODATE": strftime(
295 "%Y-%m-%d", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
296 ),
297 "ISODATETIME": strftime(
298 "%Y-%m-%dT%H:%M:%S", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
299 )
300 + "+0000",
301 "ISOTIME": strftime(
302 "%H:%M", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)
303 ),
304 "TIMESTAMP": str(int(lastmod_time)),
305 "SUMMARY": DESCRIPTION,
306 "LONG_DESCRIPTION": DESCRIPTION,
307 "DESC": LONG_DESCRIPTION,
308 "APPDATADESC": f'<p>{appdatadesc}</p>\n\t\t<p xml:lang="en">{appdatadesc}</p>',
309 "APPNAME": NAME,
310 "APPNAME_HTML": NAME_HTML,
311 "APPNAME_LOWER": NAME.lower(),
312 "APPSTREAM_ID": APPSTREAM_ID,
313 "AUTHOR": AUTHOR,
314 "AUTHOR_EMAIL": AUTHOR_EMAIL,
315 "MAINTAINER": AUTHOR,
316 "MAINTAINER_EMAIL": AUTHOR_EMAIL,
317 "MAINTAINER_EMAIL_SHA1": sha1(AUTHOR_EMAIL.encode("utf-8")).hexdigest(),
318 "PACKAGE": NAME,
319 "PY_MAXVERSION": ".".join(str(n) for n in PY_MAXVERSION),
320 "PY_MINVERSION": ".".join(str(n) for n in PY_MINVERSION),
321 "VERSION": VERSION_STRING,
322 "VERSION_SHORT": re.sub(r"(?:\.0){1,2}$", "", VERSION_STRING),
323 "URL": f"https://{DOMAIN.lower()}/",
324 # For share counts...
325 "HTTPURL": f"http://{DOMAIN.lower()}/",
326 "WX_MINVERSION": ".".join(str(n) for n in WX_MINVERSION),
327 "YEAR": strftime("%Y", gmtime(lastmod_time or os.stat(tmpl_path).st_mtime)),
328 }
329 mapping.update(iterable or {})
330
331 for key in mapping:
332 val = mapping[key]
333 tmpl_data = tmpl_data.replace(f"${{{key}}}", val)
334
335 tmpl_data = tmpl_data.replace(
336 f"{mapping['YEAR']}-{mapping['YEAR']}", mapping["YEAR"]
337 )
338
339 if Path(tmpl_path).name.startswith("debian"):
340 LONG_DESCRIPTION = longdesc_backup
341
342 out_path = Path(out_path)
343
344 if out_path.is_file():
345 with open(str(out_path), "r", encoding="UTF-8") as out:
346 data = out.read()
347
348 if data == tmpl_data:
349 return
350 elif not out_path.parent.is_dir():
351 os.makedirs(out_path.parent)
352
353 with open(str(out_path), "w", encoding="UTF-8") as out:
354 out.write(tmpl_data)
355
356
357 def setup():
358 if sys.platform == "darwin":
359 bdist_cmd = "py2app"
360 elif sys.platform == "win32":
361 bdist_cmd = "py2exe"
362 else:
363 bdist_cmd = "bdist_bbfreeze"
364
365 if "bdist_standalone" in sys.argv[1:]:
366 i = sys.argv.index("bdist_standalone")
367 sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
368
369 if bdist_cmd not in sys.argv[1:i]:
370 sys.argv.insert(i, bdist_cmd)
371 elif "bdist_bbfreeze" in sys.argv[1:]:
372 bdist_cmd = "bdist_bbfreeze"
373 elif "bdist_pyi" in sys.argv[1:]:
374 bdist_cmd = "pyi"
375 elif "py2app" in sys.argv[1:]:
376 bdist_cmd = "py2app"
377 elif "py2exe" in sys.argv[1:]:
378 bdist_cmd = "py2exe"
379
380 appdata = "appdata" in sys.argv[1:]
381 arch = None
382 bdist_appdmg = "bdist_appdmg" in sys.argv[1:]
383 bdist_pkg = "bdist_pkg" in sys.argv[1:]
384 bdist_deb = "bdist_deb" in sys.argv[1:]
385 bdist_pyi = "bdist_pyi" in sys.argv[1:]
386 buildservice = "buildservice" in sys.argv[1:]
387 setup_cfg = None
388 dry_run = "-n" in sys.argv[1:] or "--dry-run" in sys.argv[1:]
389 help = False
390 inno = "inno" in sys.argv[1:]
391 onefile = "-F" in sys.argv[1:] or "--onefile" in sys.argv[1:]
392 purge = "purge" in sys.argv[1:]
393 purge_dist = "purge_dist" in sys.argv[1:]
394 use_setuptools = "--use-setuptools" in sys.argv[1:]
395 zeroinstall = "0install" in sys.argv[1:]
396 stability = "testing"
397
398 argv = list(sys.argv[1:])
399
400 for i, arg in enumerate(reversed(argv)):
401 n = len(sys.argv) - i - 1
402 arg = arg.split("=")
403
404 if len(arg) == 2:
405 if arg[0] == "--force-arch":
406 arch = arg[1]
407 elif arg[0] in ("--cfg", "--stability"):
408 if arg[0] == "--cfg":
409 setup_cfg = arg[1]
410 else:
411 stability = arg[1]
412
413 sys.argv = sys.argv[:n] + sys.argv[n + 1 :]
414 elif arg[0] == "-h" or arg[0].startswith("--help"):
415 help = True
416
417 lastmod_time = 0
418 non_build_args = list(
419 filter(
420 lambda x: x in sys.argv[1:],
421 [
422 "bdist_appdmg",
423 "clean",
424 "purge",
425 "purge_dist",
426 "uninstall",
427 "-h",
428 "--help",
429 "--help-commands",
430 "--all",
431 "--name",
432 "--fullname",
433 "--author",
434 "--author-email",
435 "--maintainer",
436 "--maintainer-email",
437 "--contact",
438 "--contact-email",
439 "--url",
440 "--license",
441 "--licence",
442 "--description",
443 "--long-description",
444 "--platforms",
445 "--classifiers",
446 "--keywords",
447 "--provides",
448 "--requires",
449 "--obsoletes",
450 "--quiet",
451 "-q",
452 "register",
453 "--list-classifiers",
454 "upload",
455 "--use-distutils",
456 "--use-setuptools",
457 "--verbose",
458 "-v",
459 "finalize_msi",
460 ],
461 )
462 )
463
464 from DisplayCAL.util_os import which
465
466 generate_version_file()
467
468 if not sys.argv[1:]:
469 return
470
471 global NAME, NAME_HTML, AUTHOR, AUTHOR_EMAIL, DESCRIPTION, LONG_DESCRIPTION
472 global DOMAIN, PY_MAXVERSION, PY_MINVERSION
473 global VERSION_STRING, VERSION_LIN, VERSION_MAC
474 global VERSION_SRC, VERSION_TUPLE, VERSION_WIN
475 global WX_MINVERSION, APPSTREAM_ID
476
477 # Do not remove the following seemingly unused variables,
478 # I know that it seems silly, but for now we need them
479 import DisplayCAL
480 from DisplayCAL.meta import (
481 NAME,
482 NAME_HTML,
483 AUTHOR,
484 AUTHOR_EMAIL,
485 DESCRIPTION,
486 LONG_DESCRIPTION,
487 DOMAIN,
488 PY_MAXVERSION,
489 PY_MINVERSION,
490 VERSION_STRING,
491 VERSION_LIN,
492 VERSION_MAC,
493 VERSION_SRC,
494 VERSION_TUPLE,
495 VERSION_WIN,
496 WX_MINVERSION,
497 script2pywname,
498 APPSTREAM_ID,
499 get_latest_changelog_entry,
500 )
501
502 LONG_DESCRIPTION = fill(LONG_DESCRIPTION)
503
504 if not lastmod_time:
•505 lastmod_time = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
506
507 msiversion = ".".join(
508 (
509 str(VERSION_TUPLE[0]),
510 str(VERSION_TUPLE[1]),
511 str(VERSION_TUPLE[2]),
512 )
513 )
514
515 if purge or purge_dist:
516 # remove the "build", "DisplayCAL.egg-info" and
517 # "pyinstaller/bincache*" directories and their contents recursively
518
519 if dry_run:
520 print("dry run - nothing will be removed")
521
522 paths = []
523
524 if purge:
525 paths += (
526 glob.glob(str(Path(pydir, "build")))
527 + glob.glob(str(Path(pydir, NAME + ".egg-info")))
528 + glob.glob(str(Path(pydir, "pyinstaller", "bincache*")))
529 )
530 sys.argv.remove("purge")
531
532 if purge_dist:
533 paths += glob.glob(str(Path(pydir, "dist")))
534 sys.argv.remove("purge_dist")
535
536 for path in paths:
537 path = Path(path)
538
539 if path.exists():
540 if dry_run:
541 print(path)
542 continue
543
544 try:
545 shutil.rmtree(path)
546 except Exception as e:
547 print(e)
548 else:
549 print(f"Removed: {path}")
550
551 if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
552 return
553
554 if "readme" in sys.argv[1:]:
555 if not dry_run:
556 for tmpl_name in ["CHANGES", "README", "history"]:
557 for suffix in ("", "-fr"):
558 if suffix:
559 if tmpl_name == "README":
560 tmpl_name += suffix
561 else:
562 continue
563
564 replace_placeholders(
565 Path(pydir, "misc", f"{tmpl_name}.template.html"),
566 Path(pydir, f"{tmpl_name}.html"),
567 lastmod_time,
568 {"STABILITY": "Beta" if stability != "stable" else ""},
569 )
570 sys.argv.remove("readme")
571
572 if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
573 return
574
575 create_appdata = (
576 (appdata or "install" in sys.argv[1:] or "sdist" in sys.argv[1:])
577 and not help
578 and not dry_run
579 )
580
581 if (
582 "sdist" in sys.argv[1:]
583 or "install" in sys.argv[1:]
584 or "bdist_deb" in sys.argv[1:]
585 ) and not help:
586 buildservice = True
587
588 if create_appdata or buildservice:
589 with open(str(Path(pydir, "CHANGES.html")), "r", encoding="UTF-8") as f:
590 readme = f.read()
591 changelog = get_latest_changelog_entry(readme)
592
593 if create_appdata:
594 from DisplayCAL.setup import get_scripts
595 from DisplayCAL import localization as lang
596
597 scripts = get_scripts()
598 provides = [f"<python3>{NAME}</python3>"]
599
600 for script, desc in scripts:
601 provides.append(f"<binary>{script}</binary>")
602
603 provides = "\n\t\t".join(provides)
604 lang.init()
605 languages = []
606
607 for code, tdict in sorted(lang.LDICT.items()):
608 if code == "en":
609 continue
610
611 untranslated = 0
612
613 for key in tdict:
614 if key.startswith("*") and key != "*":
615 untranslated += 1
616
617 languages.append(
618 '<lang percentage="%i">%s</lang>'
619 % (round((1 - untranslated / (len(tdict) - 1.0)) * 100), code)
620 )
621
622 languages = "\n\t\t".join(languages)
623 tmpl_name = APPSTREAM_ID + ".appdata.xml"
624 misc_tmpl_name = Path(pydir, "misc", tmpl_name)
625 dist_tmpl_name = Path(pydir, "dist", tmpl_name)
626 replace_placeholders(
627 misc_tmpl_name,
628 dist_tmpl_name,
629 lastmod_time,
630 {
631 "APPDATAPROVIDES": provides,
632 "LANGUAGES": languages,
633 "CHANGELOG": format_changelog(changelog, "appstream"),
634 },
635 )
636
637 if appdata:
638 sys.argv.remove("appdata")
639
640 if buildservice and not dry_run:
641 replace_placeholders(
642 Path(pydir, "misc", "debian.copyright"),
643 Path(pydir, "dist", "copyright"),
644 lastmod_time,
645 )
646
647 if "buildservice" in sys.argv[1:]:
648 sys.argv.remove("buildservice")
649
650 if bdist_deb:
651 bdist_args = ["bdist_rpm"]
652
653 if not arch:
654 arch = get_platform().split("-")[1]
655 bdist_args += ["--force-arch=" + arch]
656
657 i = sys.argv.index("bdist_deb")
658 sys.argv = sys.argv[:i] + bdist_args + sys.argv[i + 1 :]
659
660 if bdist_pyi:
661 i = sys.argv.index("bdist_pyi")
662 sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
663
664 if "-F" in sys.argv[1:]:
665 sys.argv.remove("-F")
666
667 if "--onefile" in sys.argv[1:]:
668 sys.argv.remove("--onefile")
669
670 if inno and sys.platform == "win32":
671 tmpl_types = ["pyi" if bdist_pyi else bdist_cmd]
672
673 if zeroinstall:
674 tmpl_types.extend(["0install", "0install-per-user"])
675
676 for tmpl_type in tmpl_types:
677 inno_template_path = Path(pydir, "misc", f"{NAME}-Setup-{tmpl_type}.iss")
678 with open(inno_template_path, "r") as inno_template:
679 print(f"inno_template_path: {inno_template_path}")
680 template = inno_template.read()
681 # print(template)
682 inno_arch_raw = arch or get_platform().split("-")[1]
683 inno_arch = "x64" if inno_arch_raw == "amd64" else inno_arch_raw
684 inno_script = template % {
685 "AppCopyright": f"© {strftime('%Y')} {AUTHOR}",
686 "AppName": NAME,
687 "AppArch": inno_arch_raw,
688 "InnoArch": inno_arch,
689 "AppVerName": VERSION_STRING,
690 "AppPublisher": AUTHOR,
691 "AppPublisherURL": f"https://{DOMAIN}/",
692 "AppSupportURL": f"https://{DOMAIN}/",
693 "AppUpdatesURL": f"https://{DOMAIN}/",
694 "VersionInfoVersion": ".".join(map(str, VERSION_TUPLE)),
695 "VersionInfoTextVersion": VERSION_STRING,
696 "AppVersion": VERSION_STRING,
697 "Platform": get_platform(),
698 "PythonVersion": f"{sys.version_info[0]}.{sys.version_info[1]}",
699 "URL": f"https://{DOMAIN}/",
700 "HTTPURL": f"http://{DOMAIN}/",
701 }
702 inno_path = Path(
703 "dist",
704 inno_template_path.name.replace(
705 bdist_cmd,
706 f"{bdist_cmd}.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}",
707 ),
708 )
709 print(f"inno_path: {inno_path}")
710
711 if not dry_run:
712 dist_path = Path("dist")
713
714 if not dist_path.exists():
715 os.makedirs(dist_path)
716
717 with open(inno_path, "wb") as inno_file:
718 inno_file.write(inno_script.encode("MBCS", "replace"))
719
720 sys.argv.remove("inno")
721
722 if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
723 return
724
725 if "finalize_msi" in sys.argv[1:]:
726 if msilib is None:
727 raise RuntimeError(
728 "finalize_msi requires the stdlib msilib module, which is not "
729 "available in this Python version."
730 )
731 db = msilib.OpenDatabase(
732 rf"dist\{NAME}-{msiversion}.win32-py{sys.version_info[0]}.{sys.version_info[1]}.msi",
733 msilib.MSIDBOPEN_TRANSACT,
734 )
735 view = db.OpenView("SELECT Value FROM Property WHERE Property = 'ProductCode'")
736 view.Execute(None)
737 record = view.Fetch()
738 productcode = record.GetString(1)
739 view.Close()
740 msilib.add_data(
741 db,
742 "Directory",
743 [("ProgramMenuFolder", "TARGETDIR", ".")], # Directory # Parent
744 ) # DefaultDir
745 msilib.add_data(
746 db,
747 "Directory",
748 [
749 (
750 "MenuDir", # Directory
751 "ProgramMenuFolder", # Parent
752 NAME.upper()[:6] + "~1|" + NAME,
753 )
754 ],
755 ) # DefaultDir
756 msilib.add_data(
757 db,
758 "Icon",
759 [
760 (
761 NAME + ".ico", # Name
762 msilib.Binary(
763 str(Path(pydir, NAME, "theme", "icons", NAME + ".ico"))
764 ),
765 )
766 ],
767 ) # Data
768 msilib.add_data(
769 db,
770 "Icon",
771 [
772 (
773 "uninstall.ico", # Name
774 msilib.Binary(
775 str(
776 Path(pydir, NAME, "theme", "icons", NAME + "-uninstall.ico")
777 )
778 ),
779 )
780 ],
781 ) # Data
782 msilib.add_data(
783 db,
784 "RemoveFile",
785 [
786 (
787 "MenuDir", # FileKey
788 NAME, # Component
789 None, # FileName
790 "MenuDir", # DirProperty
791 2,
792 )
793 ],
794 ) # InstallMode
795 msilib.add_data(
796 db,
797 "Registry",
798 [
799 (
800 "DisplayIcon", # Registry
801 -1, # Root
802 rf"Software\Microsoft\Windows\CurrentVersion\Uninstall\{productcode}",
803 "DisplayIcon", # Name
804 r"[icons]%s.ico" % NAME, # Value
805 NAME,
806 )
807 ],
808 ) # Component
809 msilib.add_data(
810 db,
811 "Shortcut",
812 [
813 (
814 NAME, # Shortcut
815 "MenuDir", # Directory
816 NAME.upper()[:6] + "~1|" + NAME, # Name
817 NAME, # Component
818 r"[TARGETDIR]pythonw.exe", # Target
819 rf'"[TARGETDIR]Scripts\{NAME}"', # Arguments
820 None, # Description
821 None, # Hotkey
822 f"{NAME}.ico", # Icon
823 None, # IconIndex
824 None, # ShowCmd
825 NAME,
826 )
827 ],
828 ) # WkDir
829 msilib.add_data(
830 db,
831 "Shortcut",
832 [
833 (
834 "CHANGES", # Shortcut
835 "MenuDir", # Directory
836 "CHANGES|CHANGES", # Name
837 NAME, # Component
838 rf"[{NAME}]CHANGES.html", # Target
839 None, # Arguments
840 None, # Description
841 None, # Hotkey
842 None, # Icon
843 None, # IconIndex
844 None, # ShowCmd
845 NAME,
846 )
847 ],
848 ) # WkDir
849 msilib.add_data(
850 db,
851 "Shortcut",
852 [
853 (
854 "LICENSE", # Shortcut
855 "MenuDir", # Directory
856 "LICENSE|LICENSE", # Name
857 NAME, # Component
858 rf"[{NAME}]LICENSE.txt", # Target
859 None, # Arguments
860 None, # Description
861 None, # Hotkey
862 None, # Icon
863 None, # IconIndex
864 None, # ShowCmd
865 NAME,
866 )
867 ],
868 ) # WkDir
869 msilib.add_data(
870 db,
871 "Shortcut",
872 [
873 (
874 "README", # Shortcut
875 "MenuDir", # Directory
876 "README|README", # Name
877 NAME, # Component
878 rf"[{NAME}]README.html", # Target
879 None, # Arguments
880 None, # Description
881 None, # Hotkey
882 None, # Icon
883 None, # IconIndex
884 None, # ShowCmd
885 NAME,
886 )
887 ],
888 ) # WkDir
889 msilib.add_data(
890 db,
891 "Shortcut",
892 [
893 (
894 "Uninstall", # Shortcut
895 "MenuDir", # Directory
896 "UNINST|Uninstall", # Name
897 NAME, # Component
898 r"[SystemFolder]msiexec", # Target
899 r"/x" + productcode, # Arguments
900 None, # Description
901 None, # Hotkey
902 "uninstall.ico", # Icon
903 None, # IconIndex
904 None, # ShowCmd
905 "SystemFolder",
906 )
907 ],
908 ) # WkDir
909
910 if not dry_run:
911 db.Commit()
912
913 sys.argv.remove("finalize_msi")
914
915 if len(sys.argv) == 1 or (len(sys.argv) == 2 and dry_run):
916 return
917
918 if zeroinstall:
919 sys.argv.remove("0install")
920
921 if bdist_appdmg:
922 sys.argv.remove("bdist_appdmg")
923
924 if bdist_pkg:
925 sys.argv.remove("bdist_pkg")
926
927 if (
928 not zeroinstall
929 and not buildservice
930 and not appdata
931 and not bdist_appdmg
932 and not bdist_pkg
933 ) or sys.argv[1:]:
934 print(sys.argv[1:])
935 from DisplayCAL.setup import setup
936
937 setup()
938
939 if dry_run or help:
940 return
941
942 if buildservice:
943 # Create control files
944 mapping = {
945 "POST": open(Path(pydir, "util", "rpm_postinstall.sh"), "r").read().strip(),
946 "POSTUN": open(Path(pydir, "util", "rpm_postuninstall.sh"), "r")
947 .read()
948 .strip(),
949 "CHANGELOG": format_changelog(changelog, "rpm"),
950 }
951 tgz_file_path = Path(pydir, "dist", f"{NAME}-{VERSION_STRING}.tar.gz")
952
953 if tgz_file_path.is_file():
954 with open(tgz_file_path, "rb") as f:
955 mapping["MD5"] = md5(f.read()).hexdigest()
956
957 for tmpl_name in (
958 "PKGBUILD",
959 "debian.changelog",
960 "debian.control",
961 "debian.copyright",
962 "debian.rules",
963 f"{NAME}.changes",
964 f"{NAME}.dsc",
965 f"{NAME}.spec",
966 "appimage.yml",
967 Path("0install", "PKGBUILD"),
968 Path("0install", "debian.changelog"),
969 Path("0install", "debian.control"),
970 Path("0install", "debian.rules"),
971 Path("0install", f"{NAME}.dsc"),
972 Path("0install", f"{NAME}.spec"),
973 ):
974 tmpl_path = Path(pydir, "misc", tmpl_name)
975 replace_placeholders(
976 tmpl_path, Path(pydir, "dist", tmpl_name), lastmod_time, mapping
977 )
978
979 if bdist_deb:
980 # Read setup.cfg
981 cfg = RawConfigParser()
982 cfg.read(Path(pydir, "setup.cfg"))
983 # Get dependencies
984 dependencies = [
985 val.strip().split(None, 1)
986 for val in cfg.get("bdist_rpm", "Requires").split(",")
987 ]
988
989 # Convert dependency format:
990 # 'package >= version' to 'package (>= version)'
991 for i in range(len(dependencies)):
992 if len(dependencies[i]) > 1:
993 dependencies[i][1] = f"({dependencies[i][1]})"
994
995 dependencies[i] = " ".join(dependencies[i])
996
997 release = 1 # TODO: parse setup.cfg
998 rpm_filename = Path(pydir, "dist", f"{NAME}-{VERSION_STRING}-{release}.{arch}.rpm")
999
1000 if not dry_run:
1001 # remove target directory (and contents) if it already exists
1002 target_dir = Path(pydir, "dist", f"{NAME}-{VERSION_STRING}")
1003
1004 if target_dir.exists():
1005 shutil.rmtree(target_dir)
1006
1007 if Path(f"{target_dir}.orig").exists():
1008 shutil.rmtree(f"{target_dir}.orig")
1009
1010 # use alien to create deb dir from rpm package
1011 retcode = subprocess.call(
1012 ["alien", "-c", "-g", "-k", rpm_filename.name], cwd=Path(pydir, "dist")
1013 )
1014
1015 if retcode != 0:
1016 sys.exit(retcode)
1017
1018 # update changelog
1019 shutil.copy2(
1020 Path(pydir, "dist", "debian.changelog"),
1021 Path(pydir, "dist", f"{NAME}-{VERSION_STRING}", "debian", "changelog"),
1022 )
1023 # update rules
1024 shutil.copy2(
1025 Path(pydir, "misc", "alien.rules"),
1026 Path(pydir, "dist", f"{NAME}-{VERSION_STRING}", "debian", "rules"),
1027 )
1028 # update control
1029 control_filename = Path(
1030 pydir, "dist", f"{NAME}-{VERSION_STRING}", "debian", "control"
1031 )
1032 shutil.copy2(Path(pydir, "dist", "debian.control"), control_filename)
1033
1034 # create deb package
1035 retcode = subprocess.call(["chmod", "+x", "./debian/rules"], cwd=target_dir)
1036 retcode = subprocess.call(["./debian/rules", "binary"], cwd=target_dir)
1037
1038 if retcode:
1039 sys.exit(retcode)
1040
1041 if setup_cfg or ("bdist_msi" in sys.argv[1:] and use_setuptools):
1042 shutil.copy2(Path(pydir, "setup.cfg.backup"), Path(pydir, "setup.cfg"))
1043
1044 if bdist_pyi:
1045 # create an executable using pyinstaller
1046 retcode = subprocess.call(
1047 [
1048 sys.executable,
1049 Path(pydir, "pyinstaller", "pyinstaller.py"),
1050 "--workpath",
1051 Path(pydir, "build", f"pyi.{get_platform()}-{sys.version_info[0]}.{sys.version_info[1]}"),
1052 "--distpath",
1053 Path(pydir, "dist", f"pyi.{get_platform()}-{sys.version_info[0]}.{sys.version_info[1]}"),
1054 Path(pydir, "misc", f"{NAME}.pyi.spec"),
1055 ]
1056 )
1057
1058 if retcode != 0:
1059 sys.exit(retcode)
1060
1061 if zeroinstall:
1062 from xml.dom import minidom
1063
1064 # Create/update 0install feeds
1065 from DisplayCAL.setup import get_scripts
1066
1067 scripts = sorted(
1068 (script2pywname(script), desc) for script, desc in get_scripts()
1069 )
1070 cmds = []
1071
1072 for script, desc in scripts:
1073 cmdname = "run"
1074
1075 if script != NAME:
1076 cmdname += "-" + script.replace(NAME + "-", "")
1077
1078 cmds.append((cmdname, script, desc))
1079
1080 # Get archive digest
1081 extract = f"{NAME}-{VERSION_STRING}"
1082 archive_name = f"{extract}.tar.gz"
1083 archive_path = Path(pydir, "dist", archive_name)
1084
1085 from DisplayCAL.util_os import fs_enc
1086
1087 p = subprocess.Popen(
1088 ["0install", "digest", str(archive_path).encode(fs_enc), extract],
1089 stdout=subprocess.PIPE,
1090 cwd=pydir,
1091 )
1092 stdout, stderr = p.communicate()
1093 print(stdout)
1094 hash_ = re.search(r"(sha\d+\w+[=_][0-9a-f]+)", stdout.strip().decode())
1095
1096 if not hash_:
1097 raise SystemExit(p.wait())
1098
1099 hash_ = hash_.groups()[0]
1100
1101 for tmpl_name in (
1102 "7z.xml",
1103 "argyllcms.xml",
1104 f"{NAME}.xml",
1105 f"{NAME}-linux.xml",
1106 f"{NAME}-mac.xml",
1107 f"{NAME}-win32.xml",
1108 "numpy.xml",
1109 "SDL.xml",
1110 "pyglet.xml",
1111 "pywin32.xml",
1112 "wmi.xml",
1113 "wxpython.xml",
1114 "comtypes.xml",
1115 "faulthandler.xml",
1116 "netifaces.xml",
1117 "protobuf.xml",
1118 "pychromecast.xml",
1119 "requests.xml",
1120 "zeroconf.xml",
1121 ):
1122 dist_path = Path(pydir, "dist", "0install", tmpl_name)
1123 create = not dist_path.is_file()
1124
1125 if create:
1126 tmpl_path = Path(pydir, "misc", "0install", tmpl_name)
1127 replace_placeholders(tmpl_path, dist_path, lastmod_time)
1128
1129 if tmpl_name.startswith(NAME):
1130 with open(dist_path) as dist_file:
1131 xml = dist_file.read()
1132 domtree = minidom.parseString(xml)
1133
1134 # Get interface
1135 interface = domtree.getElementsByTagName("interface")[0]
1136 # Get languages
1137 langs = [
1138 Path(lang).suffix[0]
1139 for lang in glob.glob(str(Path(NAME, "lang", "*.json")))
1140 ]
1141 # Get architecture groups
1142 groups = domtree.getElementsByTagName("group")
1143
1144 if groups:
1145 # Get main group
1146 group0 = groups[0]
1147 # Add languages
1148 group0.setAttribute("langs", " ".join(langs))
1149
1150 # Update groups
1151 for i, group in enumerate(groups[-1:]):
1152 if create:
1153 # Remove dummy implementations
1154 for implementation in group.getElementsByTagName(
1155 "implementation"
1156 ):
1157 if implementation.getAttribute("released") == "0000-00-00":
1158 implementation.parentNode.removeChild(implementation)
1159
1160 # Add commands
1161 runner = domtree.createElement("runner")
1162
1163 if group.getAttribute("arch").startswith("Windows-"):
1164 runner.setAttribute("command", "run-win")
1165
1166 if group.getAttribute("arch").startswith("Linux"):
1167 python = "http://repo.roscidus.com/python/python"
1168 else:
1169 python = f"http://{DOMAIN}/0install/python.xml"
1170
1171 runner.setAttribute("interface", python)
1172 runner.setAttribute(
1173 "version", f"{PY_MINVERSION}.{PY_MINVERSION}..!3.0"
1174 )
1175
1176 for cmdname, script, desc in cmds:
1177 # Add command to group
1178 cmd = domtree.createElement("command")
1179 cmd.setAttribute("name", cmdname)
1180 cmd.setAttribute("path", f"{script}.pyw")
1181
1182 if cmdname.endswith("-apply-profiles-force"):
1183 # Forced calibration loading
1184 arg = domtree.createElement("arg")
1185 arg.appendChild(domtree.createTextNode("--force"))
1186 cmd.appendChild(arg)
1187
1188 cmd.appendChild(runner.cloneNode(True))
1189 group.appendChild(cmd)
1190
1191 # Add implementation if it does not exist yet, update otherwise
1192 match = None
1193
1194 for implementation in group.getElementsByTagName("implementation"):
1195 match = (
1196 implementation.getAttribute("version") == VERSION_STRING
1197 and implementation.getAttribute("stability") == stability
1198 )
1199
1200 if match:
1201 break
1202
1203 if not match:
1204 implementation = domtree.createElement("implementation")
1205 implementation.setAttribute("version", VERSION_STRING)
1206 implementation.setAttribute(
1207 "released", strftime("%Y-%m-%d", gmtime(lastmod_time))
1208 )
1209 implementation.setAttribute("stability", stability)
1210 digest = domtree.createElement("manifest-digest")
1211 implementation.appendChild(digest)
1212 archive = domtree.createElement("archive")
1213 implementation.appendChild(archive)
1214 else:
1215 digest = implementation.getElementsByTagName("manifest-digest")[
1216 0
1217 ]
1218
1219 for attrname in digest.attributes:
1220 # Remove existing hashes
1221 digest.removeAttribute(attrname)
1222
1223 archive = implementation.getElementsByTagName("archive")[0]
1224
1225 implementation.setAttribute("id", hash_)
1226 digest.setAttribute(*hash_.split("="))
1227
1228 # Update archive
1229 if stability == "stable":
1230 folder = ""
1231 else:
1232 folder = "&folder=snapshot"
1233
1234 archive.setAttribute("extract", extract)
1235 archive.setAttribute(
1236 "href",
1237 f"http://{DOMAIN}/download.php?version={VERSION_STRING}&"
1238 f"suffix=.tar.gz{folder}",
1239 )
1240 archive.setAttribute("size", str(os.stat(archive_path).st_size))
1241 archive.setAttribute("type", "application/x-compressed-tar")
1242 group.appendChild(implementation)
1243
1244 if create:
1245 for cmdname, script, desc in cmds:
1246 # Add entry-points to interface
1247 if (
1248 script == f"{NAME}-eeColor-to-madVR-converter"
1249 or script.endswith("-console")
1250 ):
1251 continue
1252
1253 entry_point = domtree.createElement("entry-point")
1254 entry_point.setAttribute("command", cmdname)
1255 binname = script
1256
1257 if cmdname.endswith("-force"):
1258 binname = f"{binname}-force"
1259
1260 entry_point.setAttribute("binary-name", binname)
1261 cfg = RawConfigParser()
1262 desktopbasename = f"{script}.desktop"
1263
1264 if cmdname.endswith("-apply-profiles"):
1265 desktopbasename = "z-" + desktopbasename
1266
1267 cfg.read(Path(pydir, "misc", desktopbasename))
1268
1269 for option, tagname in (
1270 ("Name", "name"),
1271 ("GenericName", "summary"),
1272 ("Comment", "description"),
1273 ):
1274 for lang in [None] + langs:
1275 if lang:
1276 suffix = f"[{lang}]"
1277 else:
1278 suffix = ""
1279
1280 option = f"{option}{suffix}"
1281
1282 if cfg.has_option("Desktop Entry", option):
1283 value = cfg.get("Desktop Entry", option)
1284
1285 if value:
1286 tag = domtree.createElement(tagname)
1287
1288 if not lang:
1289 lang = "en"
1290
1291 tag.setAttribute("xml:lang", lang)
1292 tag.appendChild(domtree.createTextNode(value))
1293 entry_point.appendChild(tag)
1294
1295 for ext, mime_type in (
1296 ("ico", "image/vnd.microsoft.icon"),
1297 ("png", "image/png"),
1298 ):
1299 icon = domtree.createElement("icon")
1300
1301 if ext == "ico":
1302 subdir = ""
1303 filename = script
1304 else:
1305 subdir = "256x256/"
1306 filename = script.lower()
1307
1308 icon.setAttribute(
1309 "href",
1310 f"http://{DOMAIN}/theme/icons/{subdir}{filename}.{ext}",
1311 )
1312 icon.setAttribute("type", mime_type)
1313 entry_point.appendChild(icon)
1314
1315 interface.appendChild(entry_point)
1316
1317 # Update feed
1318 print("Updating 0install feed", dist_path)
1319
1320 with open(dist_path, "wb") as dist_file:
1321 xml = domtree.toprettyxml(encoding="utf-8")
1322 xml = re.sub(r"\n\s+\n", "\n", xml)
1323 xml = re.sub(r"\n\s*([^<]+)\n\s*", r"\1", xml)
1324 dist_file.write(xml.encode())
1325
1326 # Sign feed
1327 zeropublish = which("0publish") or which("0publish.exe")
1328 args = []
1329
1330 if not zeropublish:
1331 zeropublish = which("0install") or which("0install.exe")
1332
1333 if zeropublish:
1334 args = [
1335 "run",
1336 "--command",
1337 "0publish",
1338 "--",
1339 "http://0install.de/feeds/ZeroInstall_Tools.xml",
1340 ]
1341
1342 if zeropublish:
1343 passphrase_path = Path(pydir, "gpg", "passphrase.txt")
1344 print("Signing", dist_path)
1345
1346 if passphrase_path.is_file():
1347 from DisplayCAL import wexpect
1348 # import wexpect
1349
1350 with open(passphrase_path) as passphrase_file:
1351 passphrase = passphrase_file.read().strip()
1352
1353 p = wexpect.spawn(
1354 zeropublish.encode(fs_enc),
1355 args + ["-x", str(dist_path).encode(fs_enc)],
1356 )
1357 p.expect(":")
1358 p.send(passphrase)
1359 p.send("\n")
1360
1361 try:
1362 p.expect(wexpect.EOF, timeout=3)
1363 except Exception:
1364 p.terminate()
1365 else:
1366 subprocess.call(
1367 [zeropublish] + args + ["-x", str(dist_path).encode(fs_enc)]
1368 )
1369 else:
1370 print("WARNING: 0publish not found, please sign the feed!")
1371
1372 # Create 0install app bundles
1373 bundle_template = Path("0install", "template.app", "Contents")
1374 bundle_template_path = Path(pydir, bundle_template)
1375
1376 if bundle_template_path.is_dir():
1377 p = subprocess.Popen(["0install", "-V"], stdout=subprocess.PIPE)
1378 stdout, stderr = p.communicate()
1379 zeroinstall_version = re.search(r" (\d(?:\.\d+)+)", stdout.decode())
1380
1381 if zeroinstall_version:
1382 zeroinstall_version = zeroinstall_version.groups()[0]
1383
1384 if zeroinstall_version < "2.8":
1385 zeroinstall_version = "2.8"
1386
1387 feed_uri = f"http://{DOMAIN}/0install/{NAME}.xml"
1388 dist_dir = Path(pydir, "dist", "0install", NAME + "-0install")
1389
1390 for script, desc in scripts + [
1391 ("0install-launcher", "0install Launcher"),
1392 ("0install-cache-manager", "0install Cache Manager"),
1393 ]:
1394 if script.endswith("-apply-profiles"):
1395 continue
1396
1397 desc = re.sub(rf"^{NAME} ", "", desc).strip()
1398
1399 if script == "0install-launcher":
1400 bundlename = NAME
1401 else:
1402 bundlename = desc
1403
1404 bundledistpath = Path(dist_dir, desc + ".app", "Contents")
1405 replace_placeholders(
1406 Path(bundle_template_path, "Info.plist"),
1407 Path(bundledistpath, "Info.plist"),
1408 lastmod_time,
1409 {
1410 "NAME": bundlename,
1411 "EXECUTABLE": script,
1412 "ID": ".".join(reversed(DOMAIN.split("."))) + "." + script,
1413 },
1414 )
1415
1416 if script.startswith(NAME):
1417 run = "0launch%s -- %s" % (
1418 re.sub(r"^%s" % NAME, " --command=run", script),
1419 feed_uri,
1420 )
1421 else:
1422 run = {
1423 "0install-launcher": "0launch --gui " + feed_uri,
1424 "0install-cache-manager": "0store manage",
1425 }.get(script)
1426
1427 replace_placeholders(
1428 Path(bundle_template_path, "MacOS", "template"),
1429 Path(bundledistpath, "MacOS", script),
1430 lastmod_time,
1431 {"EXEC": run, "ZEROINSTALL_VERSION": zeroinstall_version},
1432 )
1433 os.chmod(Path(bundledistpath, "MacOS", script), 0o755)
1434
1435 for binary in os.listdir(Path(bundle_template_path, "MacOS")):
1436 if binary == "template":
1437 continue
1438
1439 src = Path(bundle_template_path, "MacOS", binary)
1440 dst = Path(bundledistpath, "MacOS", binary)
1441
1442 if src.is_symlink():
1443 linkto = os.readlink(src)
1444
1445 if dst.is_symlink() and os.readlink(dst) != linkto:
1446 os.remove(dst)
1447
1448 if not dst.is_symlink():
1449 os.symlink(linkto, dst)
1450 else:
1451 shutil.copy2(src, dst)
1452
1453 resource_dir_path = Path(bundledistpath, "Resources")
1454
1455 if not resource_dir_path.is_dir():
1456 os.mkdir(resource_dir_path)
1457
1458 if script.startswith(NAME):
1459 iconsrc = Path(pydir, NAME, "theme", "icons", script + ".icns")
1460 else:
1461 iconsrc = Path(pydir, "0install", "ZeroInstall.icns")
1462
1463 icondst = Path(resource_dir_path, script + ".icns")
1464
1465 if iconsrc.is_file() and not icondst.is_file():
1466 shutil.copy2(iconsrc, icondst)
1467
1468 # README as .webloc file (link to homepage)
1469 with open(
1470 str(Path(dist_dir, "README.webloc")), "w", encoding="utf-8"
1471 ) as readme:
1472 readme.write(
1473 f"""<?xml version="1.0" encoding="UTF-8"?>
1474 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1475 <plist version="1.0">
1476 <dict>
1477 <key>URL</key>
1478 <string>https://{DOMAIN}/</string>
1479 </dict>
1480 </plist>
1481 """
1482 )
1483 # Copy LICENSE.txt
1484 shutil.copy2(Path(pydir, "LICENSE.txt"), Path(dist_dir, "LICENSE.txt"))
1485
1486 if bdist_appdmg:
1487 create_appdmg(zeroinstall)
1488
1489 if bdist_pkg:
1490 version_dir = Path(pydir, "dist", VERSION_STRING)
1491 replace_placeholders(
1492 Path(pydir, "misc", NAME + ".pkgproj"),
1493 Path(version_dir, NAME + "-" + VERSION_STRING + ".pkgproj"),
1494 lastmod_time,
1495 {"PYDIR": pydir},
1496 )
1497 shutil.move(
1498 Path(
1499 pydir,
1500 "dist",
1501 f"py2app.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}",
1502 f"{NAME}-{VERSION_STRING}",
1503 ),
1504 version_dir,
1505 )
1506 os.rename(Path(version_dir, f"{NAME}-{VERSION_STRING}"), Path(version_dir, NAME))
1507
1508 if (
1509 subprocess.call(
1510 [
1511 "/usr/local/bin/packagesbuild",
1512 "-v",
1513 Path(version_dir, f"{NAME}-{VERSION_STRING}.pkgproj"),
1514 ]
1515 )
1516 == 0
1517 ):
1518 # Success
1519 os.rename(
1520 Path(version_dir, f"{NAME}.pkg"),
1521 Path(version_dir, f"{NAME}-{VERSION_STRING}.pkg"),
1522 )
1523
1524
1525 if __name__ == "__main__":
1526 setup()