Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
Port Windows packaging scripts to Python (draft)
Freya Lupend0882042e5a2
diff --git a/build-tools/ci-scripts/sign-windows-package-at-notary-service.py b/build-tools/ci-scripts/sign-windows-package-at-notary-service.pynew file mode 100644index 0000000000..7abca19aa6--- /dev/null+++ b/build-tools/ci-scripts/sign-windows-package-at-notary-service.py@@ -0,0 +1,33 @@+import argparse+import os.path+from os import environ+import subprocess+import sys++# command-line args parsing+parser = argparse.ArgumentParser()+parser.add_argument("pkg_root", action='store', help="Specify the package root")+args = parser.parse_args()+pkg_root = args.pkg_root++print(f"Signing binaries in {pkg_root}")+if not os.path.isdir(pkg_root):+ print(f"ERROR: No packaging dir {pkg_root}")+ exit(1)++KRITACI_WINDOWS_SIGN_CONFIG = environ.get('KRITACI_WINDOWS_SIGN_CONFIG')+if not KRITACI_WINDOWS_SIGN_CONFIG:+ print("ERROR: %KRITACI_WINDOWS_SIGN_CONFIG% not set")+ exit(1)+if not os.path.isfile(KRITACI_WINDOWS_SIGN_CONFIG):+ print(f"ERROR: No signing config file found: {KRITACI_WINDOWS_SIGN_CONFIG}")+ exit(1)++with open("files-to-sign.txt", 'w') as toSign:+ with os.scandir(pkg_root) as pkg_files:+ for entry in pkg_files:+ if entry.is_file() and entry.name.endswith(('.exe', '.com', '.dll', '.pyd')):+ print(entry.path, file=toSign)++ commandToRun = "python.exe -u ci-notary-service/signwindowsbinaries.py --config %KRITACI_WINDOWS_SIGN_CONFIG% --files-from files-to-sign.txt"+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True )diff --git a/packaging/windows/msix/build_msix.py b/packaging/windows/msix/build_msix.pynew file mode 100644index 0000000000..e749474266--- /dev/null+++ b/packaging/windows/msix/build_msix.py@@ -0,0 +1,252 @@+from os import environ+import os.path+import shutil+import glob+import subprocess+import sys+import warnings++if not environ.get('OUTPUT_DIR'):+ environ['OUTPUT_DIR'] = fr"{os.getcwd()}\out"+if not environ.get('KRITA_DIR'):+ if not environ.get('KRITA_INSTALLER'):+ print("ERROR: KRITA_DIR and KRITA_INSTALLER not specified, one of them must be set.")+ exit(1)++# For CI, define both KRITA_DIR and KRITA_SHELLEX.+# Do not use KRITA_SHELLEX if building outside of CI, unless you+# don't mind this script modifying the contents of KRITA_DIR.+if environ.get('KRITA_INSTALLER'):+ if environ.get('KRITA_SHELLEX'):+ print("ERROR: KRITA_SHELLEX must not be set if using KRITA_INSTALLER.")+ exit(1)++# Subroutines++def get_temp_file():+ uniqueFileName = fr"{environ.get('tmp')}\bat~{environ.get('RANDOM')}.tmp"+ if os.path.isFile(uniqueFileName):+ uniqueFileName = get_temp_file()+ return uniqueFileName++def find_on_path(variable, executable):+ os.environ[variable] = shutil.which(executable)++# Begin++print("*** Krita MSIX build script ***")++if (not environ.get('WindowsSdkDir')) and environ.get('ProgramFiles(x86)'):+ environ['WindowsSdkDir'] = fr"{environ['ProgramFiles(x86)']}\Windows Kits\10"+if os.path.isfile(environ.get('WindowsSdkDir')):+ delims = glob.glob(fr"{environ['WindowsSdkDir']}\bin\10.*")+ for dir in delims:+ if os.path.isfile(fr"{environ['WindowsSdkDir']}\bin\{dir}\x64\makepri.exe"):+ environ['MAKEPRI'] = fr"{environ['WindowsSdkDir']}\bin\{dir}\x64\makepri.exe"+ if os.path.isfile(fr"{environ['WindowsSdkDir']}\bin\{dir}\x64\makeappx.exe"):+ environ['MAKEAPPX'] = fr"{environ['WindowsSdkDir']}\bin\{dir}\x64\makeappx.exe"+ if os.path.isfile(fr"{environ['WindowsSdkDir']}\bin\{dir}\x64\signtool.exe"):+ environ['SIGNTOOL'] = fr"{environ['WindowsSdkDir']}\bin\{dir}\x64\signtool.exe"+ if (not environ['MAKEPRI']) and os.path.isfile(fr"{environ['WindowsSdkDir']}\bin\x64\makepri.exe"):+ environ['MAKEPRI'] = fr"{environ['WindowsSdkDir']}\bin\x64\makepri.exe"+ if (not environ['MAKEAPPX']) and os.path.isfile(fr"{environ['WindowsSdkDir']}\bin\x64\makeappx.exe"):+ environ['MAKEAPPX'] = fr"{environ['WindowsSdkDir']}\bin\x64\makeappx.exe"+ if (not environ['SIGNTOOL']) and os.path.isfile(fr"{environ['WindowsSdkDir']}\bin\x64\signtool.exe"):+ environ['SIGNTOOL'] = fr"{environ['WindowsSdkDir']}\bin\x64\signtool.exe"++if not environ.get('MAKEPRI'):+ print("ERROR: makepri not found")+ exit(1)++if not environ.get('MAKEAPPX'):+ print("ERROR: makeappx not found")+ exit(1)++if not environ.get('SIGNTOOL'):+ print("ERROR: signtool not found")+ exit(1)++environ['SCRIPT_DIR'] = sys.argv[0]+os.mkdir(environ['OUTPUT_DIR'])+++if not environ['KRITA_DIR']:++ print("\n=== Step 0: Extract files from installer")++ if not environ.get("SEVENZIP_EXE"):+ find_on_path("SEVENZIP_EXE", "7z.exe")+ if not environ.get("SEVENZIP_EXE"):+ find_on_path("SEVENZIP_EXE", "7za.exe")+ if not environ.get("SEVENZIP_EXE"):+ os.environ["SEVENZIP_EXE"] = fr"{environ.get('ProgramFiles')}\7-Zip\7z.exe"+ if not os.path.isfile(os.environ["SEVENZIP_EXE"]):+ os.environ["SEVENZIP_EXE"] = fr"{environ.get('ProgramFiles(x86)')}\\7-Zip\\7-Z.exe"+ if not os.path.isfile(os.environ["SEVENZIP_EXE"]):+ warnings.warn("7-Zip not found!")+ exit(102)++ os.mkdir(fr"{environ['OUTPUT_DIR']}\installer_content")+ commandToRun = f"{environ['SEVENZIP_EXE']} x {environ['KRITA_INSTALLER']}"+ try:+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+ except subprocess.CalledProcessError:+ warnings.warn(f"ERROR failed to extract installer {environ['KRITA_INSTALLER']}")+ exit(1)+ environ['KRITA_DIR'] = fr"{environ['OUTPUT_DIR']}\installer_content"+ shutil.rmtree(fr"{environ['KRITA_DIR']}\$PLUGINSDIR")+ os.remove(fr"{environ['KRITA_DIR']}\uninstall.exe.nsis")+ os.remove(fr"{environ['KRITA_DIR']}\uninstall.exe")+++ print("=== Step 0 done. ===")+++if environ.get('KRITA_SHELLEX'):++ print("\n=== Step 0: Copy files for shell extension")++ shellex = fr"{environ['KRITA_DIR']}\shellex"+ try:+ os.mkdir(shellex)+ except:+ warnings.warn("ERROR mkdir shellex failed")+ exit(1)+ try:+ shutil.copy(fr"{environ['KRITA_SHELLEX']}\krita.ico", shellex)+ except:+ warnings.warn("ERROR copying krita.ico failed")+ exit(1)+ try:+ shutil.copy(fr"{environ['KRITA_SHELLEX']}\kritafile.ico", shellex)+ except:+ warnings.warn("ERROR copying kritafile.ico failed")+ exit(1)+ try:+ shutil.copy(fr"{environ['KRITA_SHELLEX']}\kritashellex32.dll", shellex)+ except:+ warnings.warn("ERROR copying kritashellex32.dll failed")+ exit(1)+ try:+ shutil.copy(fr"{environ['KRITA_SHELLEX']}\kritashellex64.dll", shellex)+ except:+ warnings.warn("ERROR copying kritashellex64.dll failed")+ exit(1)+ # Optional files:+ try:+ shutil.copy(fr"{environ['KRITA_SHELLEX']}\kritashellex32.pdb", shellex)+ except:+ pass+ try:+ shutil.copy(fr"{environ['KRITA_SHELLEX']}\kritashellex64.pdb", shellex)+ except:+ pass++ print("=== Step 0 done. ===")++# Sanity checks:+if not os.path.isfile(fr"{environ['KRITA_DIR']}\bin\krita.exe"):+ warnings.warn(fr'ERROR: KRITA_DIR is set to "{environ['KRITA_DIR']}" but {environ['KRITA_DIR']}\bin\krita.exe" does not exist!')+ exit(1)+if not os.path.isfile(fr"{environ['KRITA_DIR']}\shellex\kritashellex64.dll"):+ warnings.warn(fr'ERROR: "{environ['KRITA_DIR']}\shellex\kritashellex64.dll" does not exist!')+ exit(1)+if os.path.isfile(fr"{environ['KRITA_DIR']}\bin\.debug"):+ warnings.warn("ERROR: Package dir seems to contain debug symbols [gcc/mingw].")+ exit(1)+if os.path.isfile(fr"{environ['KRITA_DIR']}\bin\*.pdb"):+ warnings.warn("ERROR: Package dir seems to contain debug symbols [msvc].")+ exit(1)+if os.path.isdir(fr"{environ['KRITA_DIR']}\$PLUGINSDIR"):+ warnings.warn("")+ exit(1)+if os.path.isfile(fr"{environ['KRITA_DIR']}\uninstall.exe.nsis"):+ warnings.warn('ERROR: You did not remove "uninstall.exe.nsis."')+ exit(1)+if os.path.isfile(fr"{environ['KRITA_DIR']}\uninstall.exe*"):+ warnings.warn('ERROR: You did not remove "uninstall.exe*".')+ exit(1)+++print("\n=== Step 1: Generate resources.pri ===")++commandToRun = r'"%MAKEPRI%" new /pr "%SCRIPT_DIR%pkg" /mn "%SCRIPT_DIR%manifest.xml" /cf "%SCRIPT_DIR%priconfig.xml" /o /of "%OUTPUT_DIR%\resources.pri"'+try:+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+except subprocess.CalledProcessError:+ warnings.warn("ERROR running makepri")+ exit(1)++print("=== Step 1 done. ===")+++print("\n=== Step 2: Generate file mapping list ===")++environ['ASSETS_DIR'] = fr"{environ['SCRIPT_DIR']}pkg\Assets"+environ['MAPPING_OUT'] = fr"{environ['OUTPUT_DIR']}\mapping.txt"++OUT_TEMP = get_temp_file()+print(f"Writing list to temporary file {OUT_TEMP}")++print("[Files]", file=OUT_TEMP)+print(fr'"{environ['SCRIPT_DIR']}manifest.xml" "AppxManifest.xml"', file=OUT_TEMP)+print(fr'"{environ['OUTPUT_DIR']}\resources.pri" "Resources.pri"', file=OUT_TEMP)++# Krita application files:+for f in os.scandir(environ['KRITA_DIR']):+ print(fr'"{f}" "krita\{os.path.relpath(f, environ['KRITA_DIR'])}"', file=OUT_TEMP)++# Assets:+for f in os.scandir(environ['ASSETS_DIR']):+ print(fr'"{f}" "Assets\{os.path.relpath(f, environ['ASSETS_DIR'])}"', file=OUT_TEMP)++shutil.copy(OUT_TEMP, environ['MAPPING_OUT'])+os.remove(OUT_TEMP)++print(f'Written mapping file to "{environ['MAPPING_OUT']}"')+print("=== Step 2 done. ===")+++print("\n=== Step 3: Make MSIX with makeappx.exe ===")++r"""+(this is a comment block...)++For reference, the MSIX Packaging tool uses the following command arguments:+ pack /v /o /l /nv /nfv /f "%UserProfile%\AppData\Local\Packages\Microsoft.MsixPackagingTool_8wekyb3d8bbwe\LocalState\DiagOutputDir\Logs\wox1ifkc.h0i.txt" /p "D:\dev\krita\msix\Krita-testing_4.3.0.0_x64__svcxxs8w6n55m.msix"++The arguments stands for:+ pack: Creates a package.+ /v: Enable verbose logging output to the console.+ /o: Overwrites the output file if it exists. If you don't specify this option or the /no option, the user is asked whether they want to overwrite the file.+ /l: Used for localized packages. The default validation trips on localized packages. This options disables only that specific validation, without requiring that all validation be disabled.+ /nv: Skips semantic validation. If you don't specify this option, the tool performs a full validation of the package.+ /nfv: ???+ /f <mapping file>: Specifies the mapping file.+ /p <output package name>: Specifies the app package or bundle.+"""++commandToRun = r'"%MAKEAPPX%" pack /v /f "%OUTPUT_DIR%\mapping.txt" /p "%OUTPUT_DIR%\krita.msix" /o'+try:+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+except subprocess.CalledProcessError:+ warnings.warn("ERROR running makeappx")+ exit(1)++print(f"\nMSIX generated as {environ['OUTPUT_DIR']}\\krita.msix")++if environ.get['SIGNTOOL_SIGN_FLAGS']:+ print("Signing MSIX...")+ commandToRun = r'"%SIGNTOOL%" sign %SIGNTOOL_SIGN_FLAGS% /fd sha256 "%OUTPUT_DIR%\krita.msix"'+try:+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+except subprocess.CalledProcessError:+ warnings.warn("ERROR running signtool\n" ++ "If you need to specify a PFX keyfile and its password, run:\n" ++ r' set SIGNTOOL_SIGN_FLAGS=/f "absolute_path_to_keyfile.pfx" /p password')+ exit(1)+++print("=== Step 3 done. ===")++print("*** Script completed ***")diff --git a/packaging/windows/package-complete.py b/packaging/windows/package-complete.pynew file mode 100644index 0000000000..def8540c44--- /dev/null+++ b/packaging/windows/package-complete.py@@ -0,0 +1,653 @@+#!/usr/bin/env python++# SPDX-FileCopyrightText: 2021 L. E. Segovia <[email protected]>+# SPDX-License-Identifier: GPL-2.0-or-later++# This Python script is meant to prepare a Krita package folder to be zipped or+# to be a base for the installer.++import argparse+import glob+import itertools+import os+import re+import pathlib+import shutil+import subprocess+import sys+import warnings+++# Subroutines++def choice(prompt="Is this ok?"):+ c = input(f"{prompt} [y/n] ")+ if c == "y":+ return True+ else:+ return False+++def find_on_path(variable, executable):+ os.environ[variable] = shutil.which(executable)+++def prompt_for_file(prompt):+ user_input = input(f"{prompt} ")+ if not len(user_input):+ return None+ result = os.path.isfile(user_input)+ if result is None:+ print("Input does not point to valid dir!")+ return prompt_for_file(prompt)+ else:+ return os.path.realpath(user_input)+++def prompt_for_dir(prompt):+ user_input = input(f"{prompt} ")+ if not len(user_input):+ return None+ result = os.path.isdir(user_input)+ if result is None:+ print("Input does not point to valid dir!")+ return prompt_for_dir(prompt)+ else:+ return os.path.realpath(user_input)+++print(f"Krita Windows packaging script")+++# command-line args parsing+parser = argparse.ArgumentParser()++basic_options = parser.add_argument_group("Basic options")+basic_options.add_argument("--no-interactive", action='store_true',+ help="Run without interactive prompts. When not specified, the script will prompt for some of the parameters.")+basic_options.add_argument(+ "--package-name", action='store', help="Specify the package name", required=True)++path_options = parser.add_argument_group("Path options")+path_options.add_argument("--src-dir", action='store',+ help="Specify Krita source dir. If unspecified, this will be determined from the script location")+path_options.add_argument("--deps-install-dir", action='store',+ help="Specify deps install dir")+path_options.add_argument("--krita-install-dir", action='store',+ help="Specify Krita install dir")++special_options = parser.add_argument_group("Special options")+special_options.add_argument("--pre-zip-hook", action='store',+ help="Specify a script to be called before packaging the zip archive, can be used to sign the binaries")++args = parser.parse_args()++# Check environment config++if os.environ.get("SEVENZIP_EXE") is None:+ find_on_path("SEVENZIP_EXE", "7z.exe")+if os.environ.get("SEVENZIP_EXE") is None:+ find_on_path("SEVENZIP_EXE", "7za.exe")+if os.environ.get("SEVENZIP_EXE") is None:+ os.environ["SEVENZIP_EXE"] = f"{os.environ['ProgramFiles']}\\7-Zip\\7-Z.exe"+ if not os.path.isfile(os.environ["SEVENZIP_EXE"]):+ os.environ["SEVENZIP_EXE"] = "{}\\7-Zip\\7-Z.exe".format(+ os.environ["ProgramFiles(x86)"])+ if not os.path.isfile(os.environ["SEVENZIP_EXE"]):+ warnings.warn("7-Zip not found!")+ exit(102)+print(f"7-Zip: {os.environ['SEVENZIP_EXE']}")++if not os.environ.get("MINGW_BIN_DIR"):+ find_on_path("MINGW_BIN_DIR_MAKE_EXE", "mingw32-make.exe")+ if not os.environ.get['MINGW_BIN_DIR_MAKE_EXE']:+ if not args.no_interactive:+ os.environ['MINGW_BIN_DIR_MAKE_EXE'] = prompt_for_file("Provide path to mingw32-make.exe of mingw-w64")+ if not os.environ.get['MINGW_BIN_DIR_MAKE_EXE']:+ warnings.warn("ERROR: mingw-w64 not found!")+ exit(102)+ os.environ['MINGW_BIN_DIR'] = os.path.dirname(os.environ['MINGW_BIN_DIR_MAKE_EXE'])+ else:+ os.environ['MINGW_BIN_DIR'] = os.path.dirname(os.environ['MINGW_BIN_DIR_MAKE_EXE'])+ print(f"Found mingw on PATH: {os.environ['MINGW_BIN_DIR_MAKE_EXE']}")+ if not args.no_interactive:+ status = choice("Is this correct?")+ if not status:+ os.environ['MINGW_BIN_DIR_MAKE_EXE'] = prompt_for_dir("Provide path to mingw32-make.exe of mingw-w64")+ if not os.environ['MINGW_BIN_DIR_MAKE_EXE']:+ warnings.warn("ERROR: mingw-w64 not found!")+ exit(102)+ os.environ['MINGW_BIN_DIR'] = os.path.dirname(os.environ['MINGW_BIN_DIR_MAKE_EXE'])+print(f"mingw-w64: {os.environ['MINGW_BIN_DIR']}")++HAVE_FXC_EXE = None++# Windows SDK is needed for windeployqt to get d3dcompiler_xx.dll+if os.environ.get("WindowsSdkDir") is None and os.environ.get("ProgramFiles(x86)") is not None:+ os.environ["WindowsSdkDir"] = "{}\\Windows Kits\\10".format(+ os.environ["ProgramFiles(x86)"])+if os.path.isdir(os.environ["WindowsSdkDir"]):+ f = os.environ["WindowsSdkDir"]+ if os.path.isfile(f"{f}\\bin\\d\\fxc.exe"):+ os.environ["HAVE_FXC_EXE"] = True+ else:+ delims = glob.glob(f"{f}\\bin\\10.*")+ for f in delims:+ if os.path.isfile(f"{f}\\x64\\fxc.exe"):+ HAVE_FXC_EXE = True+if HAVE_FXC_EXE is None:+ os.environ["WindowsSdkDir"] = None+ warnings.warn("Windows SDK 10 with fxc.exe not found")+ warnings.warn(+ "If Qt was built with ANGLE (dynamic OpenGL) support, the package might not work properly on some systems!")+else:+ print(+ f"Windows SDK 10 with fxc.exe found on {os.environ['WindowsSdkDir']}")++KRITA_SRC_DIR = None++if args.src_dir is not None:+ KRITA_SRC_DIR = args.src_dir++if KRITA_SRC_DIR is None:+ _temp = sys.argv[0]+ if os.path.dirname(_temp).endswith("\\packaging\\windows"):+ _base = pathlib.PurePath(_temp)+ if os.path.isfile(f"{_base.parents[2]}\\CMakeLists.txt"):+ if os.path.isfile(f"{_base.parents[2]}\\3rdparty\\CMakeLists.txt"):+ KRITA_SRC_DIR = os.path.realpath(_base.parents[2])+ print("Script is running inside Krita source dir")++if KRITA_SRC_DIR is None:+ if args.no_interactive:+ KRITA_SRC_DIR = prompt_for_dir("Provide path of Krita src dir")+ if KRITA_SRC_DIR is None:+ warnings.warn("ERROR: Krita src dir not found!")+ exit(102)+print(f"Krita src: {KRITA_SRC_DIR}")++DEPS_INSTALL_DIR = None++if args.deps_install_dir is not None:+ DEPS_INSTALL_DIR = args.deps_install_dir+if DEPS_INSTALL_DIR is None:+ DEPS_INSTALL_DIR = f"{os.getcwd()}\\i_deps"+ print(f"Using default deps install dir: {DEPS_INSTALL_DIR}")+ if not args.no_interactive:+ status = choice()+ if not status:+ DEPS_INSTALL_DIR = prompt_for_dir(+ "Provide path of deps install dir")+ if DEPS_INSTALL_DIR is None:+ warnings.warn("ERROR: Deps install dir not set!")+ exit(102)+print(f"Deps install dir: {DEPS_INSTALL_DIR}")++KRITA_INSTALL_DIR = None++if args.krita_install_dir is not None:+ KRITA_INSTALL_DIR = args.krita_install_dir+if KRITA_INSTALL_DIR is None:+ KRITA_INSTALL_DIR = f"{os.getcwd()}\\i"+ print(f"Using default Krita install dir: {KRITA_INSTALL_DIR}")+ if not args.no_interactive:+ status = choice()+ if not status:+ KRITA_INSTALL_DIR = prompt_for_dir(+ "Provide path of Krita install dir")+ if KRITA_INSTALL_DIR is None:+ warnings.warn("ERROR: Krita install dir not set!")+ exit(102)+print(f"Krita install dir: {KRITA_INSTALL_DIR}")++# Simple checking+if not os.path.isdir(DEPS_INSTALL_DIR):+ warnings.warn("ERROR: Cannot find the deps install folder!")+ exit(1)+if not os.path.isdir(KRITA_INSTALL_DIR):+ warnings.warn("ERROR: Cannot find the krita install folder!")+ exit(1)+# Amyspark: paths with spaces are automagically handled by Python!++pkg_name = args.package_name+print(f"Package name is {pkg_name}")++pkg_root = f"{os.getcwd()}\\{pkg_name}"+print(f"Packaging dir is {pkg_root}\n")+if os.path.isdir(pkg_root):+ warnings.warn(+ "ERROR: Packaging dir already exists! Please remove or rename it first.")+ exit(1)+if os.path.isfile(f"{pkg_root}.zip"):+ warnings.warn(+ "ERROR: Packaging zip already exists! Please remove or rename it first.")+ exit(1)+if os.path.isfile(f"{pkg_root}-dbg.zip"):+ warnings.warn(+ "ERROR: Packaging debug zip already exists! Please remove or rename it first.")+ exit(1)++if not args.no_interactive:+ status = choice()+ if not status:+ exit(255)+ print("")++# Initialize clean PATH+os.environ["PATH"] = r"%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0" + "\\"+os.environ["PATH"] = fr"{os.environ['MINGW_BIN_DIR']};{DEPS_INSTALL_DIR}\bin;{os.environ['PATH']}"+++print("\nTrying to guess compiler version...")+for arg in ("g++", "clang++"):+ commandToRun = f"{arg} --version"+ ret = subprocess.call(commandToRun, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)+ if ret != 1:+ os.environ['CC'] = arg+if not os.environ['CC']:+ warnings.warn("ERROR: No working compiler.")+ exit(1)+output = subprocess.check_output(f"{os.environ['CC']} --version", shell=True, text=True)+GCCversionLines = output.splitlines()+GCC_VERSION_LINE = ""+for versionLine in GCCversionLines:+ if re.search("g\+\+", versionLine):+ GCC_VERSION_LINE = versionLine+# The space in "clang " is essential to detect+# the version line and not the InstalledDir+if not GCC_VERSION_LINE:+ for versionLine in GCCversionLines:+ if re.search("clang ", versionLine):+ GCC_VERSION_LINE = versionLine+if not GCC_VERSION_LINE:+ warnings.warn("ERROR: Failed to get version of g++.")+ exit(1)+print(f"-- {GCC_VERSION_LINE}")+IS_TDM = False+IS_MSYS = False+IS_CLANG = False+if re.search("tdm64", GCC_VERSION_LINE):+ print("Compiler looks like TDM64-GCC")+ IS_TDM = True+if re.search("MSYS", GCC_VERSION_LINE):+ print("Compiler looks like MSYS GCC")+ IS_MSYS = True+if re.search("clang", GCC_VERSION_LINE):+ print("Compiler looks like Clang")+ IS_CLANG = True+else:+ print("Compiler looks like plain old MinGW64")+IS_LLVM_MINGW = False+IS_MSYS_CLANG = False+if IS_CLANG:+ # Look for the multiarch target binary dirs. Unfortunately there is+ # no surefire way to detect a llvm-mingw toolchain.+ if os.path.isdir(f"{os.environ['MINGW_BIN_DIR']}\\..\\i686-w64-mingw32\\bin\\") and \+ os.path.isdir(f"{os.environ['MINGW_BIN_DIR']}\\..\\x86_64-w64-mingw32\\bin\\"):+ print("Toolchain looks like llvm-mingw")+ IS_LLVM_MINGW = True+ else:+ print("Toolchain does not look like llvm-mingw, assuming MSYS Clang")+ IS_MSYS_CLANG = True++print("\nTrying to guess target architecture...")+OBJDUMP = False+for arg in ("objdump", "llvm-objdump"):+ commandToRun = f"{arg} --version"+ ret = subprocess.call(commandToRun, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)+ if ret != 1:+ OBJDUMP = arg+if not OBJDUMP:+ warnings.warn("ERROR: objdump is not working.")+ exit(1)+output = subprocess.check_output(fr"{OBJDUMP} -f {KRITA_INSTALL_DIR}\bin\krita.exe", shell=True, text=True)+targetArchLines = output.splitlines()+TARGET_ARCH_LINE = ""+for archLine in targetArchLines:+ if re.search("i386", archLine):+ TARGET_ARCH_LINE = archLine+if not TARGET_ARCH_LINE:+ print("Possible LLVM objdump, trying to detect architecture...")+ if re.search("coff", archLine):+ TARGET_ARCH_LINE = archLine+print(f"-- {TARGET_ARCH_LINE}")+IS_x64 = False+if not re.search("x64-64", TARGET_ARCH_LINE):+ print("Target looks like x86")+else:+ print("Target looks like x64")+ IS_x64 = True++print("\nTesting for objcopy...")+commandToRun = "objcopy --version"+try:+ subprocess.check_call(commandToRun, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)+except subprocess.CalledProcessError:+ warnings.warn("ERROR: objcopy is not working.")+ exit(1)++print("\nTesting for strip...")+commandToRun = "strip --version"+try:+ subprocess.check_call(commandToRun, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)+except subprocess.CalledProcessError:+ warnings.warn("ERROR: strip is not working.")+ exit(1)+++print("\nCreating base directories...")++try:+ os.makedirs(f"{pkg_root}", exist_ok=True)+ os.makedirs(f"{pkg_root}\\bin", exist_ok=True)+ os.makedirs(f"{pkg_root}\\etc", exist_ok=True)+ os.makedirs(f"{pkg_root}\\lib", exist_ok=True)+ os.makedirs(f"{pkg_root}\\share", exist_ok=True)+except:+ warnings.warn("ERROR: Cannot create packaging dir tree!")+ exit(1)++print("\nCopying GCC libraries...")+os.environ['STDLIBS_DIR'] = os.environ['MINGW_BIN_DIR']+if IS_TDM:+ if not IS_x64:+ # TDM-GCC x86+ os.environ['STDLIBS'] = "libgomp-1"+ else:+ # TDM-GCC x64+ os.environ['STDLIBS'] = "libgomp_64-1"+elif IS_MSYS:+ if not IS_x64:+ # msys-mingw-w64 x86+ os.environ['STDLIBS'] = "libgcc_s_dw2-1 libgomp-1 libstdc++-6 libwinpthread-1 libatomic-1 libiconv-2 zlib1 libexpat-1 libintl-8 libssl-1_1 libcrypto-1_1"+ else:+ # msys-mingw-w64 x64+ os.environ['STDLIBS'] = "libgcc_s_seh-1 libgomp-1 libstdc++-6 libwinpthread-1 libatomic-1 libiconv-2 zlib1 libexpat-1 libintl-8 libssl-1_1-x64 libcrypto-1_1-x64"+elif IS_MSYS_CLANG:+ if not IS_x64:+ # msys-mingw-w64-clang64 x86+ os.environ['STDLIBS'] = "libomp libssp-0 libunwind libc++ libwinpthread-1 libiconv-2 zlib1 libexpat-1 libintl-8 libssl-1_1 libcrypto-1_1"+ else:+ # msys-mingw-w64-clang64 x64+ os.environ['STDLIBS'] = "libomp libssp-0 libunwind libc++ libwinpthread-1 libiconv-2 zlib1 libexpat-1 libintl-8 libssl-1_1-x64 libcrypto-1_1-x64"+elif IS_LLVM_MINGW:+ # llvm-mingw+ os.environ['STDLIBS'] = "libc++ libomp libssp-0 libunwind libwinpthread-1"+ # The toolchain does not include all of the DLLs in the compiler bin dir,+ # so we need to copy them from the cross target bin dir.+ if not IS_x64:+ os.environ['STDLIBS_DIR'] = r"%MINGW_BIN_DIR%\..\i686-w64-mingw32\bin"+ else:+ os.environ['STDLIBS_DIR'] = r"%MINGW_BIN_DIR%\..\x86_64-w64-mingw32\bin"+else:+ if not IS_x64:+ # mingw-w64 x86+ os.environ['STDLIBS'] = "libgcc_s_dw2-1 libgomp-1 libstdc++-6 libwinpthread-1"+ else:+ # mingw-w64 x64+ os.environ['STDLIBS'] = "libgcc_s_seh-1 libgomp-1 libstdc++-6 libwinpthread-1"++for lib in os.environ['STDLIBS']:+ shutil.copy(fr"{os.environ['STDLIBS_DIR']}\{lib}.dll", fr"{pkg_root}\bin")++print("\nCopying files...")+# krita.exe+shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\krita.exe", f"{pkg_root}\\bin\\")+shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\krita.com", f"{pkg_root}\\bin\\")+if os.path.isfile(f"{KRITA_INSTALL_DIR}\\bin\\krita.pdb"):+ shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\krita.pdb", f"{pkg_root}\\bin\\")+# kritarunner.exe+shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\kritarunner.exe", f"{pkg_root}\\bin\\")+if os.path.isfile(f"{KRITA_INSTALL_DIR}\\bin\\kritarunner.pdb"):+ shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\kritarunner.pdb",+ f"{pkg_root}\\bin\\")+shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\kritarunner_com.com",+ f"{pkg_root}\\bin\\")++if os.path.isfile(f"{KRITA_INSTALL_DIR}\\bin\\FreehandStrokeBenchmark.exe"):+ shutil.copy(f"{KRITA_INSTALL_DIR}\\bin\\FreehandStrokeBenchmark.exe", f"{pkg_root}\\bin\\")+ subprocess.run(["xcopy", "/S", "/Y", "/I",+ f"{DEPS_INSTALL_DIR}\\bin\\data\\", f"{pkg_root}\\bin\\data\\"])++# qt.conf -- to specify the location to Qt translations+shutil.copy(fr"{KRITA_SRC_DIR}\packaging\windows\qt.conf", fr"{pkg_root}\bin")+# DLLs from bin/+print("INFO: Copying all DLLs except Qt5 * from bin/")+files = glob.glob(f"{KRITA_INSTALL_DIR}\\bin\\*.dll")+pdbs = glob.glob(f"{KRITA_INSTALL_DIR}\\bin\\*.pdb")+for f in itertools.chain(files, pdbs):+ if not os.path.basename(f).startswith("Qt5"):+ shutil.copy(f, f"{pkg_root}\\bin")+files = glob.glob(f"{DEPS_INSTALL_DIR}\\bin\\*.dll")+for f in files:+ pdb = f"{os.path.dirname(f)}\\{os.path.splitext(os.path.basename(f))[0]}.pdb"+ if not os.path.basename(f).startswith("Qt5"):+ shutil.copy(f, f"{pkg_root}\\bin")+ if os.path.isfile(pdb):+ shutil.copy(pdb, f"{pkg_root}\\bin")+# symsrv.yes for Dr. Mingw+shutil.copy(f"{DEPS_INSTALL_DIR}\\bin\\symsrv.yes", f"{pkg_root}\\bin")+# DLLs from lib/+print("INFO: Copying all DLLs from lib/ (deps)")+files = glob.glob(fr"{DEPS_INSTALL_DIR}\lib\*.dll")+for f in files:+ shutil.copy(f, fr"{pkg_root}\bin")+# Boost, there might be more than one leftover but we can't really do much+files = glob.glob(fr"{DEPS_INSTALL_DIR}\bin\libboost_system-*.dll")+for f in files:+ shutil.copy(f, fr"{pkg_root}\bin")+# KF5 plugins may be placed at different locations depending on how Qt is built+subprocess.run(["xcopy", "/S", "/Y", "/I",+ f"{DEPS_INSTALL_DIR}\\lib\\plugins\\imageformats\\", f"{pkg_root}\\bin\\imageformats\\"])+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\plugins\\imageformats\\".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\bin\\imageformats\\"])+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\plugins\\kf5\\".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\bin\\kf5\\"])++# Copy the sql drivers explicitly+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\plugins\\sqldrivers\\".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\bin\\sqldrivers"], check=True)++# Qt Translations+# it seems that windeployqt does these, but only * some * of these???+os.makedirs(f"{pkg_root}\\bin\\translations", exist_ok=True)+files = glob.glob(f"{DEPS_INSTALL_DIR}\\translations\\qt_*.qm")+for f in files:+ # Exclude qt_help_*.qm+ if not os.path.basename(f).startswith("qt_help"):+ shutil.copy(f, f"{pkg_root}\\bin\\translations")++# Krita plugins+subprocess.run(["xcopy", "/Y", "{}\\lib\\kritaplugins\\*.dll".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\lib\\kritaplugins\\"], check=True)+subprocess.run(["xcopy", "/Y", "{}\\lib\\kritaplugins\\*.pdb".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\lib\\kritaplugins\\"], check=True)+if os.path.isdir(f"{DEPS_INSTALL_DIR}\\lib\\krita-python-libs"):+ subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\lib\\krita-python-libs".format(DEPS_INSTALL_DIR), f"{pkg_root}\\lib\\krita-python-libs"], check=True)+if os.path.isdir(f"{KRITA_INSTALL_DIR}\\lib\\krita-python-libs"):+ subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\lib\\krita-python-libs".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\lib\\krita-python-libs"], check=True)+if os.path.isdir(f"{DEPS_INSTALL_DIR}\\lib\\site-packages"):+ subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\lib\\site-packages".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\lib\\site-packages"], check=True)++# MLT plugins and their data+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\lib\\mlt".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\lib\\mlt"], check=True)+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\mlt".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\share\\mlt"], check=True)++# Fontconfig+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\etc\\fonts".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\etc\\fonts"], check=True)++# Share+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\color".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\share\\color"], check=True)+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\color-schemes".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\share\\color-schemes"], check=True)+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\icons".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\share\\icons"], check=True)+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\krita".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\share\\krita"])+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\kritaplugins".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\share\\kritaplugins"], check=True)+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\kf5".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\share\\kf5"], check=True)+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\mime".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\share\\mime"], check=True)+# Python libs are copied by share\krita above+# Copy locale to bin+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\locale".format(+ KRITA_INSTALL_DIR), f"{pkg_root}\\bin\\locale"])+subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\share\\locale".format(+ DEPS_INSTALL_DIR), f"{pkg_root}\\bin\\locale"], check=True)++# Copy shortcut link from source (can't create it dynamically)+shutil.copy(f"{KRITA_SRC_DIR}\\packaging\\windows\\krita.lnk", pkg_root)+shutil.copy(+ f"{KRITA_SRC_DIR}\\packaging\\windows\\krita-minimal.lnk", pkg_root)+shutil.copy(+ f"{KRITA_SRC_DIR}\\packaging\\windows\\krita-animation.lnk", pkg_root)++QMLDIR_ARGS = ["--qmldir", f"{DEPS_INSTALL_DIR}\\qml"]+if os.path.isdir(f"{KRITA_INSTALL_DIR}\\lib\\qml"):+ subprocess.run(["xcopy", "/S", "/Y", "/I",+ f"{KRITA_INSTALL_DIR}\\lib\\qml", f"{pkg_root}\\bin\\"], check=True)+ # This doesn't really seem to do anything+ QMLDIR_ARGS.extend(["--qmldir", f"{KRITA_INSTALL_DIR}\\lib\\qml"])++# For some reason windowsdeployqt skips installing Layouts QML plugin,+# so we need to copy it manually+if os.path.isdir(fr"{DEPS_INSTALL_DIR}\qml\QtQuick\Layouts"):+ subprocess.run(["xcopy", "/S", "/Y", "/I", "{}\\qml\\QtQuick\\Layouts".format(+ DEPS_INSTALL_DIR), fr"{pkg_root}\bin\QtQuick\Layouts"], check=True)+++# windeployqt+subprocess.run(["windeployqt.exe", *QMLDIR_ARGS, "--release", "-gui", "-core", "-concurrent", "-network", "-printsupport", "-svg",+ "-xml", "-sql", "-qml", "-quick", "-quickwidgets", f"{pkg_root}\\bin\\krita.exe", f"{pkg_root}\\bin\\krita.dll"], check=True)++# ffmpeg+if os.path.exists(f"{DEPS_INSTALL_DIR}\\bin\\ffmpeg.exe"):+ shutil.copy(f"{DEPS_INSTALL_DIR}\\bin\\ffmpeg.exe", f"{pkg_root}\\bin")+ shutil.copy(f"{DEPS_INSTALL_DIR}\\bin\\ffprobe.exe", f"{pkg_root}\\bin")+ shutil.copy(f"{DEPS_INSTALL_DIR}\\bin\\ffmpeg_LICENSE.txt",+ f"{pkg_root}\\bin")+ shutil.copy(f"{DEPS_INSTALL_DIR}\\bin\\ffmpeg_README.txt",+ f"{pkg_root}\\bin")++# Copy embedded Python+subprocess.run(["xcopy", "/S", "/Y", "/I",+ f"{DEPS_INSTALL_DIR}\\python", f"{pkg_root}\\python"], check=True)+if os.path.exists(f"{pkg_root}\\python\\python.exe"):+ os.remove(f"{pkg_root}\\python\\python.exe")+if os.path.exists(f"{pkg_root}\\python\\pythonw.exe"):+ os.remove(f"{pkg_root}\\python\\pythonw.exe")++# Remove Python cache files+for d in os.walk(pkg_root):+ pycache = f"{d[0]}\\__pycache__"+ if os.path.isdir(pycache):+ print(f"Deleting Python cache {pycache}")+ shutil.rmtree(pycache)++if os.path.exists(f"{pkg_root}\\lib\\site-packages"):+ print(f"Deleting unnecessary Python packages")+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\packaging*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\pip*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\ply*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\pyparsing*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\PyQt_builder*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\setuptools.pth"):+ os.remove(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\setuptools*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\sip*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\toml*"):+ shutil.rmtree(f)+ for f in glob.glob(f"{pkg_root}\\lib\\site-packages\\easy-install.pth"):+ os.remove(f)++print("\nSplitting debug info from binaries...")++def split_debug(arg1, arg2):+ print(f"Splitting debug info of {arg2}")+ commandToRun = f"objcopy --only-keep-debug {arg1} {arg1}.debug"+ try:+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+ except subprocess.CalledProcessError:+ exit(1)+ # If the debug file is small enough then consider there being no debug info.+ # Discard these files since they somehow make gdb crash.+ if os.path.size(f"{arg1}.debug") <= 2048:+ print(f"Discarding {arg2}.debug")+ os.remove(f"{arg1}.debug")+ return 0+ if not os.path.isdir(os.path.dirname(f"{arg1}.debug")):+ os.mkdir(os.path.dirname(f"{arg1}.debug"))+ shutil.move(f"{arg1}.debug", f"{os.path.dirname(f"{arg1}.debug")}\\")+ commandToRun = f"strip --strip-debug {arg1}"+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+ # Add debuglink+ # FIXME: There is a problem with gdb that cause it to output this warning+ # FIXME: "warning: section .gnu_debuglink not found in xxx.debug"+ # FIXME: I tried adding a link to itself but this kills drmingw :(+ commandToRun = fr'objcopy --add-gnu-debuglink="{os.path.dirname(f"{arg1}")}.debug\{os.path.basename(arg1)}.debug" {arg1}'+ try:+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+ except subprocess.CalledProcessError as status:+ return status.returncode+ return 0++split_debug(fr"{pkg_root}\bin\krita.exe", r"bin\krita.exe")+split_debug(fr"{pkg_root}\bin\krita.com", r"bin\krita.com")+split_debug(fr"{pkg_root}\bin\kritarunner.exe", r"bin\kritarunner.exe")+split_debug(fr"{pkg_root}\bin\kritarunner.com", r"bin\kritarunner.com")+# Find all DLLs+files = glob.glob(fr"{pkg_root}\*.dll")+for f in files:+ split_debug(f, os.path.relpath(f, pkg_root))+# Find all Python native modules+files = glob.glob(fr"{pkg_root}\share\krita\pykrita\*.pyd")+for f in files:+ split_debug(f, os.path.relpath(f, pkg_root))+files = glob.glob(fr"{pkg_root}\lib\krita-python-libs\*.pyd")+for f in files:+ split_debug(f, os.path.relpath(f, pkg_root))+files = glob.glob(fr"{pkg_root}\lib\site-packages\*.pyd")+for f in files:+ split_debug(f, os.path.relpath(f, pkg_root))+++if args.pre_zip_hook:+ print("Running pre-zip hook...")+ subprocess.run(["cmd", "/c", args.pre_zip_hook,+ f"{pkg_root}\\"], check=True)++print("\nPackaging stripped binaries...")+subprocess.run([os.environ["SEVENZIP_EXE"], "a", "-tzip",+ f"{pkg_name}.zip", f"{pkg_root}\\", "-xr!**\*.pdb"], check=True)+print("--------\n")+print("Packaging debug info...")+# (note that the top-level package dir is not included)+subprocess.run([os.environ["SEVENZIP_EXE"], "a", "-tzip",+ f"{pkg_name}-dbg.zip", "-r", f"{pkg_root}\\**\\*.pdb"], check=True)+print("--------\n")++print("\n")+print(f"Krita packaged as {pkg_name}.zip")+if os.path.isfile(f"{pkg_name}-dbg.zip"):+ print(f"Debug info packaged as {pkg_name}-dbg.zip")+print(f"Packaging dir is {pkg_root}")+print("NOTE: Do not create installer with packaging dir. Extract from")+print(f" {pkg_name}.zip instead")+print("and do _not_ run krita inside the extracted directory because it will")+print(" create extra unnecessary files.\n")+print("Please remember to actually test the package before releasing it.\n")diff --git a/packaging/windows/sign-package.py b/packaging/windows/sign-package.pynew file mode 100644index 0000000000..a90d4d4f43--- /dev/null+++ b/packaging/windows/sign-package.py@@ -0,0 +1,60 @@+import argparse+from os import environ+import os.path+import glob+import subprocess+import sys++# command-line args parsing+parser = argparse.ArgumentParser()+parser.add_argument("pkg_root", action='store', help="Specify the package root", required=True)+args = parser.parse_args()+pkg_root = args.pkg_root++if not environ.get('SIGNTOOL'):+ # Find Windows SDK for signtool.exe+ if (not environ.get('WindowsSdkDir')) and environ.get('ProgramFiles(x86)'):+ environ['WindowsSdkDir'] = fr"{environ['ProgramFiles(x86)']}\Windows Kits\10"+ if os.path.isfile(environ.get('WindowsSdkDir')):+ sdkDir = environ["WindowsSdkDir"]+ delims = glob.glob(fr"{sdkDir}\bin\10.*")+ for dir in delims:+ if os.path.isfile(sdkDir + fr"bin\{dir}\x64\signtool.exe"):+ environ['SIGNTOOL'] = fr"{sdkDir}\{dir}\bin\x86\signtool.exe"+ if not environ.get('SIGNTOOL'):+ if os.path.isfile(fr"{sdkDir}\bin\x64\signtool.exe"):+ environ['SIGNTOOL'] = fr"{sdkDir}\bin\x86\signtool.exe"+ if not environ.get('SIGNTOOL'):+ print("ERROR: signtool not found")+ exit(1)+++if not environ.get('SIGNTOOL_SIGN_FLAGS'):+ print("ERROR: Please set environment variable SIGNTOOL_SIGN_FLAGS")+ exit(1)+ # This is what I used for testing:+ # set "SIGNTOOL_SIGN_FLAGS=/f "C:\Users\Alvin\MySPC.pfx" /t http://timestamp.verisign.com/scripts/timstamp.dll"++print(f"Signing binaries in {pkg_root}")+if not os.path.isdir(pkg_root):+ print(f"ERROR: No packaging dir {pkg_root}")+ exit(1)++with os.scandir(pkg_root) as pkg_files:+ for entry in pkg_files:+ if entry.is_file() and entry.name.endswith(('.exe', '.com', '.dll', '.pyd')):+ # Check for existing signature+ commandToRun = f'"%SIGNTOOL%" verify /q /pa "{entry.name}"'+ try:+ subprocess.check_call(commandToRun, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)+ except subprocess.CalledProcessError as status:+ if status.returncode == 1:+ print(f"Signing {entry.path}")+ try:+ commandToRun = f'"%SIGNTOOL%" sign %SIGNTOOL_SIGN_FLAGS% "{entry.path}"'+ subprocess.check_call(commandToRun, stdout=sys.stdout, stderr=sys.stderr, shell=True)+ except subprocess.CalledProcessError as status:+ print(f"ERROR: Got exit code {status.returncode} from signtool!")+ exit(1)+ else:+ print(f"Not signing {entry.path} - file already signed")