File: postinstall.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (408 lines) | stat: -rw-r--r-- 14,767 bytes parent folder | download
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
# -*- coding: utf-8 -*-

from io import StringIO
from subprocess import call
from os.path import basename, splitext
import os
import shutil
import sys
import traceback

from DisplayCAL.meta import name
from DisplayCAL.util_os import relpath, safe_glob, which

recordfile_name = "INSTALLED_FILES"

if sys.stdout and hasattr(sys.stdout, "isatty") and not sys.stdout.isatty():
    sys.stdout = StringIO()

if sys.platform == "win32":
    try:
        create_shortcut
    # this function is only available within bdist_wininst installers
    except NameError:
        try:
            from pythoncom import (
                CoCreateInstance,
                CLSCTX_INPROC_SERVER,
                IID_IPersistFile,
            )
            from win32com.shell import shell
            import win32con
        except ImportError:

            def create_shortcut(*args):
                pass

        else:

            def create_shortcut(*args):
                shortcut = CoCreateInstance(
                    shell.CLSID_ShellLink,
                    None,
                    CLSCTX_INPROC_SERVER,
                    shell.IID_IShellLink,
                )
                shortcut.SetPath(args[0])
                shortcut.SetDescription(args[1])
                if len(args) > 3:
                    shortcut.SetArguments(args[3])
                if len(args) > 4:
                    shortcut.SetWorkingDirectory(args[4])
                if len(args) > 5:
                    shortcut.SetIconLocation(args[5], args[6] if len(args) > 6 else 0)
                shortcut.SetShowCmd(win32con.SW_SHOWNORMAL)
                shortcut.QueryInterface(IID_IPersistFile).Save(args[2], 0)

    try:
        directory_created
    # this function is only available within bdist_wininst installers
    except NameError:

        def directory_created(path):
            pass

    try:
        file_created
    # this function is only available within bdist_wininst installers
    except NameError:
        try:
            import win32api
        except ImportError:

            def file_created(path):
                pass

        else:

            def file_created(path):
                if os.path.exists(recordfile_name):
                    installed_files = []
                    if os.path.exists(recordfile_name):
                        recordfile = open(recordfile_name, "r")
                        installed_files.extend(line.rstrip("\n") for line in recordfile)
                        recordfile.close()
                    try:
                        path.encode("ASCII")
                    except (UnicodeDecodeError, UnicodeEncodeError):
                        # the contents of the record file used by distutils
                        # must be ASCII GetShortPathName allows us to avoid
                        # any issues with encoding because it returns the
                        # short path as 7-bit string (while still being a
                        # valid path)
                        path = win32api.GetShortPathName(path)
                    installed_files.append(path)
                    recordfile = open(recordfile_name, "w")
                    recordfile.write("\n".join(installed_files))
                    recordfile.close()

    try:
        get_special_folder_path
    # this function is only available within bdist_wininst installers
    except NameError:
        try:
            from win32com.shell import shell, shellcon
        except ImportError:

            def get_special_folder_path(csidl_string):
                pass

        else:

            def get_special_folder_path(csidl_string):
                return shell.SHGetSpecialFolderPath(
                    0, getattr(shellcon, csidl_string), 1
                )


def postinstall_macos(prefix=None):
    """Do postinstall actions for macOS."""
    # TODO: implement
    pass


def postinstall_windows(prefix):
    """Do postinstall actions for Windows."""
    if prefix is None:
        # assume we are running from bdist_wininst installer
        modpath = os.path.dirname(os.path.abspath(__file__))
    else:
        # assume we are running from source dir,
        # or from install dir
        modpath = prefix

    if not os.path.exists(modpath):
        print("warning - '{}' not found".format(modpath.encode("MBCS", "replace")))
        return

    if os.path.exists(recordfile_name):
        irecordfile_name = os.path.join(modpath, "INSTALLED_FILES")
        with open(irecordfile_name, "w"):  # touch create the file
            pass
        file_created(irecordfile_name)
        shutil.copy2(recordfile_name, irecordfile_name)

    mainicon = os.path.join(modpath, "theme", "icons", f"{name}.ico")
    if not os.path.exists(mainicon):
        print("warning - '{}' not found".format(icon.encode("MBCS", "replace")))
        return

    try:
        startmenu_programs_common = get_special_folder_path("CSIDL_COMMON_PROGRAMS")
        startmenu_programs = get_special_folder_path("CSIDL_PROGRAMS")
        startmenu_common = get_special_folder_path("CSIDL_COMMON_STARTMENU")
        startmenu = get_special_folder_path("CSIDL_STARTMENU")
    except OSError:
        traceback.print_exc()
        return

    filenames = [
        filename
        for filename in safe_glob(os.path.join(sys.prefix, "Scripts", f"{name}*"))
        if not filename.endswith("-script.py")
        and not filename.endswith("-script.pyw")
        and not filename.endswith(".manifest")
        and not filename.endswith(".pyc")
        and not filename.endswith(".pyo")
        and not filename.endswith("_postinstall.py")
    ] + ["LICENSE.txt", "README.html", "Uninstall"]
    installed_shortcuts = []
    for path in (startmenu_programs_common, startmenu_programs):
        if not path:
            continue
        grppath = os.path.join(path, name)
        if path == startmenu_programs:
            group = relpath(grppath, startmenu)
        else:
            group = relpath(grppath, startmenu_common)

        if not os.path.exists(grppath):
            try:
                os.makedirs(grppath)
            except Exception:
                # maybe insufficient privileges?
                pass

        if os.path.exists(grppath):
            print(
                ("Created start menu group '{}' in {}").format(
                    name,
                    (
                        str(path, "MBCS", "replace") if not isinstance(path, str) else path
                    ).encode("MBCS", "replace"),
                )
            )
        else:
            print(
                ("Failed to create start menu group '{}' in {}").format(
                    name,
                    (
                        str(path, "MBCS", "replace") if not isinstance(path, str) else path
                    ).encode("MBCS", "replace"),
                )
            )
            continue
        directory_created(grppath)
        for filename in filenames:
            lnkname = splitext(basename(filename))[0]
            lnkpath = os.path.join(grppath, f"{lnkname}.lnk")
            if os.path.exists(lnkpath):
                try:
                    os.remove(lnkpath)
                except Exception:
                    # maybe insufficient privileges?
                    print(
                        ("Failed to create start menu entry '{}' in {}").format(
                            lnkname,
                            (
                                str(grppath, "MBCS", "replace")
                                if not isinstance(grppath, str)
                                else grppath
                            ).encode("MBCS", "replace"),
                        )
                    )
                    continue
            if not os.path.exists(lnkpath):
                if lnkname != "Uninstall":
                    tgtpath = os.path.join(modpath, filename)
                try:
                    if lnkname == "Uninstall":
                        uninstaller = os.path.join(sys.prefix, f"Remove{name}.exe")
                        if os.path.exists(uninstaller):
                            create_shortcut(
                                uninstaller,
                                lnkname,
                                lnkpath,
                                '-u "{}-wininst.log"'.format(
                                    os.path.join(sys.prefix, name)
                                ),
                                sys.prefix,
                                os.path.join(
                                    modpath,
                                    "theme",
                                    "icons",
                                    f"{name}-uninstall.ico",
                                ),
                            )
                        else:
                            # When running from a
                            # bdist_wininst or bdist_msi
                            # installer, sys.executable
                            # points to the installer
                            # executable, not python.exe
                            create_shortcut(
                                os.path.join(sys.prefix, "python.exe"),
                                lnkname,
                                lnkpath,
                                '"{}" uninstall --record="{}"'.format(
                                    os.path.join(modpath, "setup.py"),
                                    os.path.join(modpath, "INSTALLED_FILES"),
                                ),
                                sys.prefix,
                                os.path.join(
                                    modpath,
                                    "theme",
                                    "icons",
                                    f"{name}-uninstall.ico",
                                ),
                            )
                    elif lnkname.startswith(name):
                        # When running from a
                        # bdist_wininst or bdist_msi
                        # installer, sys.executable
                        # points to the installer
                        # executable, not python.exe
                        icon = os.path.join(
                            modpath,
                            "theme",
                            "icons",
                            f"{lnkname}.ico",
                        )
                        icon = mainicon if not os.path.isfile(icon) else icon
                        if filename.endswith(".exe"):
                            exe = filename
                            args = ""
                        else:
                            exe = os.path.join(sys.prefix, "pythonw.exe")
                            args = f'"{tgtpath}"'
                        create_shortcut(
                            exe,
                            lnkname,
                            lnkpath,
                            args,
                            modpath,
                            icon,
                        )
                    else:
                        create_shortcut(tgtpath, lnkname, lnkpath, "", modpath)
                except Exception:
                    # maybe insufficient privileges?
                    print(
                        ("Failed to create start menu entry '{}' in {}").format(
                            lnkname,
                            (
                                str(grppath, "MBCS", "replace")
                                if not isinstance(grppath, str)
                                else grppath
                            ).encode("MBCS", "replace"),
                        )
                    )
                    continue
                print(
                    ("Installed start menu entry '{}' to {}").format(
                        lnkname,
                        (
                            str(group, "MBCS", "replace")
                            if not isinstance(group, str)
                            else group
                        ).encode("MBCS", "replace"),
                    )
                )
            file_created(lnkpath)
            installed_shortcuts.append(filename)
        if installed_shortcuts == filenames:
            break


def postinstall_linux(prefix=None):
    """Do postinstall actions for Linux."""
    # Linux/Unix
    if prefix is None:
        prefix = sys.prefix
    if which("touch"):
        call(["touch", "--no-create", f"{prefix}/share/icons/hicolor"])
    if which("xdg-icon-resource"):
        # print("installing icon resources...")
        # for size in [16, 22, 24, 32, 48, 256]:
        # call([
        #     "xdg-icon-resource",
        #     "install",
        #     "--noupdate",
        #     "--novendor",
        #     "--size",
        #     str(size),
        #     f"{prefix}/share/{name}/theme/icons/{size}x{size}/{name}.png"
        # ])
        call(["xdg-icon-resource", "forceupdate"])
    if which("xdg-desktop-menu"):
        # print("installing desktop menu entry...")
        # call([
        #     "xdg-desktop-menu",
        #     "install",
        #     "--novendor",
        #     f"{prefix}/share/{name}/{name}.desktop"
        # ])
        call(["xdg-desktop-menu", "forceupdate"])


def postinstall(prefix=None):
    if sys.platform == "darwin":
        postinstall_macos()
    elif sys.platform == "win32":
        postinstall_windows(prefix)
    else:
        postinstall_linux(prefix)


def postuninstall(prefix=None):
    if sys.platform == "darwin":
        # TODO: implement
        pass
    elif sys.platform == "win32":
        # nothing to do
        pass
    else:
        # Linux/Unix
        if prefix is None:
            prefix = sys.prefix
        if which("xdg-desktop-menu"):
            # print("uninstalling desktop menu entry...")
            # call(["xdg-desktop-menu", "uninstall", prefix +
            # (f"/share/applications/{name}.desktop")])
            call(["xdg-desktop-menu", "forceupdate"])
        if which("xdg-icon-resource"):
            # print("uninstalling icon resources...")
            # for size in [16, 22, 24, 32, 48, 256]:
            # call(["xdg-icon-resource", "uninstall", "--noupdate", "--size",
            # str(size), name])
            call(["xdg-icon-resource", "forceupdate"])


def main():
    prefix = None
    for arg in sys.argv[1:]:
        arg = arg.split("=")
        if len(arg) == 2:
            if arg[0] == "--prefix":
                prefix = arg[1]
    try:
        if "-remove" in sys.argv[1:]:
            postuninstall(prefix)
        else:
            postinstall(prefix)
    except Exception:
        traceback.print_exc()


if __name__ == "__main__":
    main()