Skip to content
This repository has been archived by the owner on Jun 9, 2021. It is now read-only.

Commit

Permalink
fade to black (marcelotduarte#946)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelotduarte authored Feb 28, 2021
1 parent bc6dadd commit 63802f6
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 72 deletions.
5 changes: 4 additions & 1 deletion cx_Freeze/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@

import sys


def main(): # needed for console script
if __package__ == '':
if __package__ == "":
# To be able to run 'python cx_Freeze-6.*.whl/cxfreeze':
import os.path

path = os.path.dirname(os.path.dirname(__file__))
sys.path[0:0] = [path]
import cx_Freeze.cli

sys.exit(cx_Freeze.cli.main())


Expand Down
131 changes: 81 additions & 50 deletions cx_Freeze/darwintools.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,19 @@ class MachOReference:
"""Represents a linking reference from MachO file to another file."""

def __init__(
self, sourceFile: "DarwinFile", rawPath: str, resolvedPath: Optional[str]
self,
sourceFile: "DarwinFile",
rawPath: str,
resolvedPath: Optional[str],
):
"""
:param sourceFile: DarwinFile object for file in which the reference
was found
:param rawPath: The load path that appears in the file
(may include @rpath, etc.)
:param resolvedPath: The path resolved to an explicit path to a file
on system. Or None, if the path could not be resolved at the time the DarwinFile
was processed.
on system. Or None, if the path could not be resolved at the time the
DarwinFile was processed.
"""
self.sourceFile: "DarwinFile" = sourceFile
self.rawReferencePath: str = rawPath
Expand Down Expand Up @@ -76,7 +79,7 @@ def __init__(
self,
originalFilePath: str,
referencingFile: Optional["DarwinFile"] = None,
strictRPath: bool = False
strictRPath: bool = False,
):
"""
:param originalFilePath: The original path of the DarwinFile (before
Expand All @@ -90,7 +93,8 @@ def __init__(
self.referencingFile: Optional[DarwinFile] = None
self.strictRPath = strictRPath

self._buildPath: Optional[str] = None # path to file in build directory (set as part of freeze process)
# path to file in build directory (set as part of freeze process)
self._buildPath: Optional[str] = None

# commands in a Mach-O file
self.commands: List[MachOCommand] = []
Expand All @@ -99,10 +103,15 @@ def __init__(

# note: if file gets referenced twice (or more), it will only be the
# first reference that gets recorded.
self.libraryPathResolution: Dict[str, Optional[str]] = {} # mapping of raw load paths to absolute resolved paths (or None, if no resolution was determined)
self._rpath: Optional[List[str]] = None # the is of entries in the rpath in effect for this file.

# dictionary of MachOReference objects, by their paths. Path used is the resolved path, if available, and otherwise the unresolved load path.
# mapping of raw load paths to absolute resolved paths
# (or None, if no resolution was determined)
self.libraryPathResolution: Dict[str, Optional[str]] = {}
# the is of entries in the rpath in effect for this file.
self._rpath: Optional[List[str]] = None

# dictionary of MachOReference objects, by their paths.
# Path used is the resolved path, if available, and otherwise the
# unresolved load path.
self.machOReferenceForTargetPath: Dict[str, MachOReference] = {}
self.isMachO = False

Expand All @@ -127,7 +136,9 @@ def __init__(

# Create MachOReference objects for all the binaries referenced form this file.
for rawPath, resolvedPath in self.libraryPathResolution.items():
dictPath = resolvedPath # the path to use for storing in dictionary
dictPath = (
resolvedPath # the path to use for storing in dictionary
)
if resolvedPath is None:
dictPath = rawPath
if dictPath in self.machOReferenceForTargetPath:
Expand All @@ -154,16 +165,19 @@ def __str__(self):

def fileReferenceDepth(self) -> int:
"""Returns how deep this Mach-O file is in the dynamic load order."""
if self.referencingFile is not None: return self.referencingFile.fileReferenceDepth() + 1
if self.referencingFile is not None:
return self.referencingFile.fileReferenceDepth() + 1
return 0

def printFileInformation(self):
"""Prints information about the Mach-O file."""
print(f'[{self.fileReferenceDepth()}] File: "{self.originalFilePath}"')
print(" Commands:")
if len(self.commands) > 0:
for c in self.commands: print(f' {c}')
else: print(" [None]")
for c in self.commands:
print(f" {c}")
else:
print(" [None]")

# This can be included for even more detail on the problem file.
# print(" Load commands:")
Expand All @@ -173,20 +187,23 @@ def printFileInformation(self):

print(" RPath commands:")
if len(self.rpathCommands) > 0:
for rpc in self.rpathCommands: print(f' {rpc}')
else: print(" [None]")
for rpc in self.rpathCommands:
print(f" {rpc}")
else:
print(" [None]")
print(" Calculated RPath:")
rpath = self.getRPath()
if len(rpath) > 0:
for path in rpath: print(f" {path}")
else: print(" [None]")
for path in rpath:
print(f" {path}")
else:
print(" [None]")
if self.referencingFile is not None:
print("Referenced from:")
self.referencingFile.printFileInformation()
return

def getBaseName(self) -> str:
return os.path.basename( self.originalFilePath )
return os.path.basename(self.originalFilePath)

def setBuildPath(self, path: str):
self._buildPath = path
Expand Down Expand Up @@ -539,10 +556,14 @@ def recordCopiedFile(self, targetPath: str, darwinFile: DarwinFile):
self._darwinFileForBuildPath[targetPath] = darwinFile
self._darwinFileForSourcePath[darwinFile.originalFilePath] = darwinFile

def cacheReferenceTo(self, sourcePath: str, machOReference: MachOReference):
def cacheReferenceTo(
self, sourcePath: str, machOReference: MachOReference
):
self._referenceCache[sourcePath] = machOReference

def getCachedReferenceTo(self, sourcePath: str) -> Optional[MachOReference]:
def getCachedReferenceTo(
self, sourcePath: str
) -> Optional[MachOReference]:
if sourcePath in self._referenceCache:
return self._referenceCache[sourcePath]
return None
Expand All @@ -551,55 +572,65 @@ def findDarwinFileForFilename(self, fileName: str) -> Optional[DarwinFile]:
"""Attempts to locate a copied DarwinFile with the specified filename and returns that.
Otherwise returns None."""
for df in self._copiedFileList:
if df.getBaseName() == fileName: return df
if df.getBaseName() == fileName:
return df
return None

def finalizeReferences(self):
"""
This function does a final pass through the references for all the copied
DarwinFiles and attempts to clean up any remaining references that are not
already marked as copied. It covers two cases where the reference might
not be marked as copied:
1) Files where _CopyFile was called without copyDependentFiles=True (in which
the information would not have been added to the references at that time).
2) Files with broken @rpath references. We try to fix that up here by seeing
if the relevant file was located *anywhere* as part of the freeze process.
This function does a final pass through the references for all the
copied DarwinFiles and attempts to clean up any remaining references
that are not already marked as copied. It covers two cases where the
reference might not be marked as copied:
1) Files where _CopyFile was called without copyDependentFiles=True
(in which the information would not have been added to the
references at that time).
2) Files with broken @rpath references. We try to fix that up here by
seeing if the relevant file was located *anywhere* as part of the
freeze process.
"""
for copiedFile in self._copiedFileList: # DarwinFile
for reference in copiedFile.getMachOReferenceList():
if not reference.isCopied:
if reference.isResolved():
# if reference is resolve, simply check if the resolved path was otherwise
# copied and lookup the DarwinFile object.
realTargetPath = os.path.realpath(reference.resolvedReferencePath)
# if reference is resolve, simply check if the resolved
# path was otherwise copied and lookup the DarwinFile
# object.
realTargetPath = os.path.realpath(
reference.resolvedReferencePath
)
if realTargetPath in self._darwinFileForSourcePath:
reference.setTargetFile(self._darwinFileForSourcePath[realTargetPath])
reference.setTargetFile(
self._darwinFileForSourcePath[realTargetPath]
)
else:
# if reference is not resolved, look through the copied files and try to find
# a candidate, and use it if found.
# if reference is not resolved, look through the copied
# files and try to find a candidate, and use it if found.
potentialTarget = self.findDarwinFileForFilename(
fileName=os.path.basename(reference.rawReferencePath)
fileName=os.path.basename(
reference.rawReferencePath
)
)
if potentialTarget is None:
# If we cannot find any likely candidate, fail.
print(
f"\nERROR: Could not resolve RPath [{reference.rawReferencePath}] "
f"in file [{copiedFile.originalFilePath}], and could not find any "
"likely intended reference."
"\nERROR: Could not resolve RPath "
f"[{reference.rawReferencePath}] in file "
f"[{copiedFile.originalFilePath}], and could "
"not find any likely intended reference."
)
copiedFile.printFileInformation()
raise DarwinException(
f"finalizeReferences() failed to resolve path "
f"[{reference.rawReferencePath}] in file "
f"[{copiedFile.originalFilePath}]."
)
else:
print(
f"WARNING: In file [{copiedFile.originalFilePath}] guessing that "
f"{reference.rawReferencePath} resolved to "
f"{potentialTarget.originalFilePath}."
)
reference.resolvedReferencePath = potentialTarget.originalFilePath
reference.setTargetFile(potentialTarget)


print(
f"WARNING: In file [{copiedFile.originalFilePath}]"
f" guessing that {reference.rawReferencePath} "
f"resolved to {potentialTarget.originalFilePath}."
)
reference.resolvedReferencePath = (
potentialTarget.originalFilePath
)
reference.setTargetFile(potentialTarget)
16 changes: 11 additions & 5 deletions cx_Freeze/freezer.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,16 @@ def _FreezeExecutable(self, exe):
# We need to do this so the file knows what file referenced it, and can therefore
# calculate the appropriate rpath.
# (We only cache one reference.)
cachedReference = self.darwinTracker.getCachedReferenceTo(sourcePath=source)
self._CopyFile( source, target,
copyDependentFiles=True, includeMode=True,
machOReference=cachedReference )
cachedReference = self.darwinTracker.getCachedReferenceTo(
sourcePath=source
)
self._CopyFile(
source,
target,
copyDependentFiles=True,
includeMode=True,
machOReference=cachedReference,
)
else:
self._CopyFile(
source, target, copyDependentFiles=True, includeMode=True
Expand Down Expand Up @@ -410,7 +416,7 @@ def _GetDependentFiles(self, path, darwinFile: DarwinFile = None) -> List:
if reference.isResolved():
self.darwinTracker.cacheReferenceTo(
sourcePath=reference.resolvedReferencePath,
machOReference=reference
machOReference=reference,
)
else:
if not os.access(path, os.X_OK):
Expand Down
22 changes: 11 additions & 11 deletions cx_Freeze/macdist.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from distutils.core import Command
import os
import plistlib
import shutil
import subprocess
import warnings

Expand All @@ -19,7 +20,7 @@

class bdist_dmg(Command):
description = (
"create a Mac DMG disk image containing the Mac " "application bundle"
"create a Mac DMG disk image containing the Mac application bundle"
)
user_options = [
("volume-label=", None, "Volume label of the DMG disk image"),
Expand All @@ -29,7 +30,7 @@ class bdist_dmg(Command):
"Boolean for whether to include "
"shortcut to Applications in the DMG disk image",
),
("silent", "s", "suppress all output except warnings")
("silent", "s", "suppress all output except warnings"),
]

def initialize_options(self):
Expand All @@ -47,15 +48,15 @@ def buildDMG(self):
os.unlink(self.dmgName)

# Make dist folder
import shutil

self.dist_dir = os.path.join(self.buildDir, "dist")
if os.path.exists(self.dist_dir):
shutil.rmtree(self.dist_dir)
self.mkpath(self.dist_dir)

# Copy App Bundle
dest_dir = os.path.join(self.dist_dir, os.path.basename(self.bundleDir))
dest_dir = os.path.join(
self.dist_dir, os.path.basename(self.bundleDir)
)
self.copy_tree(self.bundleDir, dest_dir)

createargs = [
Expand All @@ -80,7 +81,9 @@ def buildDMG(self):

if self.applications_shortcut:
apps_folder_link = os.path.join(self.dist_dir, "Applications")
os.symlink("/Applications", apps_folder_link, target_is_directory=True)
os.symlink(
"/Applications", apps_folder_link, target_is_directory=True
)

# Create the dmg
if os.spawnvp(os.P_WAIT, "hdiutil", createargs) != 0:
Expand Down Expand Up @@ -150,7 +153,7 @@ class bdist_mac(Command):
(
"codesign-identity=",
None,
"The identity of the key to be used to " "sign the app bundle.",
"The identity of the key to be used to sign the app bundle.",
),
(
"codesign-entitlements=",
Expand All @@ -161,7 +164,7 @@ class bdist_mac(Command):
(
"codesign-deep=",
None,
"Boolean for whether to codesign using the " "--deep option.",
"Boolean for whether to codesign using the --deep option.",
),
(
"codesign-resource-rules",
Expand Down Expand Up @@ -326,9 +329,6 @@ def setRelativeReferencePaths(self, buildDir: str, binDir: str):
newReference=exePath,
VERBOSE=False,
)
pass
pass
return

def find_qt_menu_nib(self):
"""
Expand Down
11 changes: 6 additions & 5 deletions doc/src/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,12 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
("index",
"cx_freeze",
"cx_Freeze Documentation",
["Anthony Tuininga", "Marcelo Duarte"],
1,
(
"index",
"cx_freeze",
"cx_Freeze Documentation",
["Anthony Tuininga", "Marcelo Duarte"],
1,
)
]

Expand Down

0 comments on commit 63802f6

Please sign in to comment.