Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jwight/pep8 #22

Merged
merged 3 commits into from
Sep 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,18 +67,18 @@ Installation
How to use
----------

There are many ways to use this script after you installed *xUnqiue* . I will introduce two:
There are many ways to use this script after you installed *xUnique* . I will introduce two:

Xcode "build post-action" (Recommended)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#. open ``Edit Scheme`` in Xcode (shortcut:
``⌘``\ +\ ``Shift``\ +\ ``,``)
#. choose the sheme you use to run your project
#. choose the scheme you use to run your project
#. expand ``Build``, select ``Post-actions``
#. click symbol ``+`` on the left bottom corner of the right pane
#. choose ``New Run Script Action``
#. choose your selected sheme name in ``Provide build settings from``
#. choose your selected scheme name in ``Provide build settings from``
#. input commands below:

.. code-block:: bash
Expand Down Expand Up @@ -139,7 +139,7 @@ Use options in xUnique:

-v print verbose output, and generate ``debug_result.json`` file for debug.
-u uniquify project file, that is, replace UUID to MD5 digest.
-s sort project file inlcuding ``children``, ``files``, ``PBXFileReference`` and ``PBXBuildFile`` list and remove all duplicated entries in these lists. Supports both original and uniquified project file.
-s sort project file including ``children``, ``files``, ``PBXFileReference`` and ``PBXBuildFile`` list and remove all duplicated entries in these lists. Supports both original and uniquified project file.
-p sort ``PBXFileReference`` and ``PBXBuildFile`` sections in project file ordered by file names. Only works with ``-s``. Before v4.0.0, this was hard-coded in ``-s`` option and cannot be turned off. Starting from v4.0.0, without this option along with ``-s``, xUnique will sort these two types by MD5 digests, the same as Xcode does.
-c When project file was modified, xUnique quit with non-zero status. Without this option, the status code would be zero if so. This option is usually used in Git hook to submit xUnique result combined with your original new commit.

Expand Down Expand Up @@ -197,7 +197,7 @@ Authors
Contributions
-------------

- I only tested on several single projects and serveral projects with a
- I only tested on several single projects and several projects with a
subproject, so maybe there should be more unconsidered conditions. If
you get any problem, feel free to fire a Pull Request or Issue

Expand Down
6 changes: 5 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,9 @@
'Programming Language :: Objective C',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7'
],
],
entry_points="""
[console_scripts]
xunique=xUnique:cli
""",
)
69 changes: 38 additions & 31 deletions xUnique.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,19 @@
from filecmp import cmp as filecmp_cmp
from optparse import OptionParser


md5_hex = lambda a_str: hl_md5(a_str.encode('utf-8')).hexdigest().upper()
print_ng = lambda *args, **kwargs: print(*[unicode(i).encode(sys_get_fs_encoding()) for i in args], **kwargs)
#output_u8line = lambda a_unicode: print(a_unicode.encode('utf-8'), end='')
output_u8line = lambda *args : print(*[unicode(i).encode('utf-8') for i in args],end='')
# output_u8line = lambda a_unicode: print(a_unicode.encode('utf-8'), end='')
output_u8line = lambda *args: print(*[unicode(i).encode('utf-8') for i in args], end='')


def warning_print(*args, **kwargs):
new_args = list(args)
new_args[0] = '\x1B[33m{}'.format(new_args[0])
new_args[-1] = '{}\x1B[0m'.format(new_args[-1])
print_ng(*new_args, **kwargs)


def success_print(*args, **kwargs):
new_args = list(args)
new_args[0] = '\x1B[32m{}'.format(new_args[0])
Expand Down Expand Up @@ -78,7 +80,7 @@ def __init__(self, target_path, verbose=False):
self.root_hex: {'path': self.proj_root,
'new_key': md5_hex(self.proj_root),
'type': self.root_node['isa']
}
}
})
self._is_modified = False

Expand All @@ -95,7 +97,8 @@ def pbxproj_to_json(self):
raise XUniqueExit("""{}
Please check:
1. You have installed Xcode Command Line Tools and command 'plutil' could be found in $PATH;
2. The project file is not broken, such like merge conflicts, incomplete content due to xUnique failure. """.format(cpe.output))
2. The project file is not broken, such like merge conflicts, incomplete content due to xUnique failure. """.format(
cpe.output))

def __set_to_result(self, parent_hex, current_hex, current_path_key):
current_node = self.nodes[current_hex]
Expand All @@ -114,11 +117,11 @@ def __set_to_result(self, parent_hex, current_hex, current_path_key):
current_hex: {'path': '{}[{}]'.format(isa_type, cur_abs_path),
'new_key': md5_hex(cur_abs_path),
'type': isa_type
}
}
})

def get_proj_root(self):
'''PBXProject name,the root node'''
"""PBXProject name,the root node"""
pbxproject_ptn = re_compile('(?<=PBXProject ").*(?=")')
with open(self.xcode_pbxproj_path) as pbxproj_file:
for line in pbxproj_file:
Expand Down Expand Up @@ -154,7 +157,6 @@ def unique_project(self):
warning_print("Debug result json file has been written to '", debug_result_file_path, sep='')
self.substitute_old_keys()


def substitute_old_keys(self):
self.vprint('replace UUIDs and remove unused UUIDs')
key_ptn = re_compile('(?<=\s)([0-9A-Z]{24}|[0-9A-F]{32})(?=[\s;])')
Expand All @@ -174,7 +176,7 @@ def substitute_old_keys(self):
continue
# remove incorrect entry that somehow does not exist in project node tree
elif not all(self.__result.get(uuid) for uuid in key_list):
self.vprint("Some node(s) are not in generated result, remove this line :",key_list)
self.vprint("Some node(s) are not in generated result, remove this line :", key_list)
removed_lines.append(new_line)
continue
else:
Expand All @@ -196,10 +198,10 @@ def substitute_old_keys(self):
warning_print('Following lines were deleted because of invalid format or no longer being used:')
print_ng(*removed_lines, end='')

def sort_pbxproj(self, sort_pbx_by_file_name = False):
def sort_pbxproj(self, sort_pbx_by_file_name=False):
self.vprint('sort project.xpbproj file')
lines = []
removed_lines=[]
removed_lines = []
files_start_ptn = re_compile('^(\s*)files = \(\s*$')
files_key_ptn = re_compile('((?<=[A-Z0-9]{24} \/\* )|(?<=[A-F0-9]{32} \/\* )).+?(?= in )')
fc_end_ptn = '\);'
Expand Down Expand Up @@ -314,7 +316,7 @@ def file_dir_cmp(x, y):
print_ng(*removed_lines, end='')

def __unique_project(self, project_hex):
'''PBXProject. It is root itself, no parents to it'''
"""PBXProject. It is root itself, no parents to it"""
self.vprint('uniquify PBXProject')
self.vprint('uniquify PBX*Group and PBX*Reference*')
self.__unique_group_or_ref(project_hex, self.main_group_hex)
Expand All @@ -337,7 +339,7 @@ def __unique_project(self, project_hex):
self.__unique_target(target_hex)

def __unique_build_configuration_list(self, parent_hex, build_configuration_list_hex):
'''XCConfigurationList'''
"""XCConfigurationList"""
cur_path_key = 'defaultConfigurationName'
self.__set_to_result(parent_hex, build_configuration_list_hex, cur_path_key)
build_configuration_list_node = self.nodes[build_configuration_list_hex]
Expand All @@ -346,12 +348,12 @@ def __unique_build_configuration_list(self, parent_hex, build_configuration_list
self.__unique_build_configuration(build_configuration_list_hex, build_configuration_hex)

def __unique_build_configuration(self, parent_hex, build_configuration_hex):
'''XCBuildConfiguration'''
"""XCBuildConfiguration"""
cur_path_key = 'name'
self.__set_to_result(parent_hex, build_configuration_hex, cur_path_key)

def __unique_target(self, target_hex):
'''PBXNativeTarget PBXAggregateTarget'''
"""PBXNativeTarget PBXAggregateTarget"""
self.vprint('uniquify PBX*Target')
current_node = self.nodes[target_hex]
bcl_hex = current_node['buildConfigurationList']
Expand All @@ -370,7 +372,7 @@ def __unique_target(self, target_hex):
self.__unique_build_rules(target_hex, build_rule_hex)

def __unique_target_dependency(self, parent_hex, target_dependency_hex):
'''PBXTargetDependency'''
"""PBXTargetDependency"""
target_hex = self.nodes[target_dependency_hex].get('target')
if target_hex:
self.__set_to_result(parent_hex, target_dependency_hex, self.__result[target_hex]['path'])
Expand All @@ -379,9 +381,9 @@ def __unique_target_dependency(self, parent_hex, target_dependency_hex):
self.__unique_container_item_proxy(target_dependency_hex, self.nodes[target_dependency_hex]['targetProxy'])

def __unique_container_item_proxy(self, parent_hex, container_item_proxy_hex):
'''PBXContainerItemProxy'''
"""PBXContainerItemProxy"""
self.vprint('uniquify PBXContainerItemProxy')
self.__set_to_result(parent_hex, container_item_proxy_hex, ('isa','remoteInfo'))
self.__set_to_result(parent_hex, container_item_proxy_hex, ('isa', 'remoteInfo'))
cur_path = self.__result[container_item_proxy_hex]['path']
current_node = self.nodes[container_item_proxy_hex]
# re-calculate remoteGlobalIDString to a new length 32 MD5 digest
Expand All @@ -395,21 +397,21 @@ def __unique_container_item_proxy(self, parent_hex, container_item_proxy_hex):
'new_key': md5_hex(new_rg_id_path),
'type': '{}#{}'.format(self.nodes[container_item_proxy_hex]['isa'],
'remoteGlobalIDString')
}
}
})

def __unique_build_phase(self, parent_hex, build_phase_hex):
'''PBXSourcesBuildPhase PBXFrameworksBuildPhase PBXResourcesBuildPhase
"""PBXSourcesBuildPhase PBXFrameworksBuildPhase PBXResourcesBuildPhase
PBXCopyFilesBuildPhase PBXHeadersBuildPhase PBXShellScriptBuildPhase
'''
"""
self.vprint('uniquify all kinds of PBX*BuildPhase')
current_node = self.nodes[build_phase_hex]
# no useful key in some build phase types, use its isa value
bp_type = current_node['isa']
if bp_type == 'PBXShellScriptBuildPhase':
cur_path_key = 'shellScript'
elif bp_type =='PBXCopyFilesBuildPhase':
cur_path_key = ['name','dstSubfolderSpec','dstPath']
elif bp_type == 'PBXCopyFilesBuildPhase':
cur_path_key = ['name', 'dstSubfolderSpec', 'dstPath']
if not current_node.get('name'):
del cur_path_key[0]
else:
Expand All @@ -420,7 +422,7 @@ def __unique_build_phase(self, parent_hex, build_phase_hex):
self.__unique_build_file(build_phase_hex, build_file_hex)

def __unique_group_or_ref(self, parent_hex, group_ref_hex):
'''PBXFileReference PBXGroup PBXVariantGroup PBXReferenceProxy'''
"""PBXFileReference PBXGroup PBXVariantGroup PBXReferenceProxy"""
if self.nodes.get(group_ref_hex):
current_hex = group_ref_hex
if self.nodes[current_hex].get('name'):
Expand All @@ -441,7 +443,7 @@ def __unique_group_or_ref(self, parent_hex, group_ref_hex):
self.__result.setdefault('to_be_removed', []).append(group_ref_hex)

def __unique_build_file(self, parent_hex, build_file_hex):
'''PBXBuildFile'''
"""PBXBuildFile"""
current_node = self.nodes.get(build_file_hex)
if not current_node:
self.__result.setdefault('to_be_removed', []).append(build_file_hex)
Expand All @@ -455,11 +457,12 @@ def __unique_build_file(self, parent_hex, build_file_hex):
cur_path_key = self.__result[file_ref_hex]['path']
self.__set_to_result(parent_hex, build_file_hex, cur_path_key)
else:
self.vprint("PBXFileReference '", file_ref_hex, "' not found inPBXBuildFile :", build_file_hex,'. To be removed.',sep='')
self.vprint("PBXFileReference '", file_ref_hex, "' not found inPBXBuildFile :", build_file_hex,
'. To be removed.', sep='')
self.__result.setdefault('to_be_removed', []).extend((build_file_hex, file_ref_hex))

def __unique_build_rules(self, parent_hex, build_rule_hex):
'''PBXBuildRule'''
"""PBXBuildRule"""
current_node = self.nodes.get(build_rule_hex)
if not current_node:
self.vprint("PBXBuildRule '", current_node, "' not found, it will be removed.")
Expand All @@ -468,11 +471,12 @@ def __unique_build_rules(self, parent_hex, build_rule_hex):
file_type = current_node['fileType']
cur_path_key = 'fileType'
if file_type == 'pattern.proxy':
cur_path_key = ('fileType','filePatterns')
self.__set_to_result(parent_hex,build_rule_hex,cur_path_key)
cur_path_key = ('fileType', 'filePatterns')
self.__set_to_result(parent_hex, build_rule_hex, cur_path_key)


class XUniqueExit(SystemExit):
def __init__(self,value):
def __init__(self, value):
value = "\x1B[31m{}\x1B[0m".format(value)
super(XUniqueExit, self).__init__(value)

Expand Down Expand Up @@ -518,6 +522,9 @@ def main(sys_args):
if xunique.is_modified:
warning_print("File 'project.pbxproj' was modified, please add it and commit again to submit xUnique result.\nNOTICE: If you want to submit xUnique result combined with original commit, use option '-c' in command.")

def cli():
main(sys_argv)


if __name__ == '__main__':
main(sys_argv)
cli()