Beispiel #1
0
    def set_code_sign(self, code_sign_identity, provisioning_profile, development_team=None,
                      provisioning_profile_uuid=None, code_sign_entitlements=None):
        print("===> set code sign identity=%s,profile=%s,team=%s,profile_uuid=%s,entitlements=%s" %
              (code_sign_identity, provisioning_profile, development_team, provisioning_profile_uuid,
               code_sign_entitlements))
        xcode_project_file_path = self._get_xcode_project_file_path(self.project_root)
        pbx_proj_file_path = os.path.join(xcode_project_file_path, "project.pbxproj")
        pbx_project = XcodeProject.load(pbx_proj_file_path)
        ios_app_target = self._get_ios_app_target(pbx_project)
        if ios_app_target:
            target_name = ios_app_target.name
            pbx_project.set_flags(u'CODE_SIGN_IDENTITY', code_sign_identity, target_name)
            pbx_project.set_flags(u'CODE_SIGN_IDENTITY[sdk=iphoneos*]', code_sign_identity, target_name)
            pbx_project.set_flags(u'PROVISIONING_PROFILE_SPECIFIER', provisioning_profile, target_name)
            if development_team:
                pbx_project.set_flags(u'DEVELOPMENT_TEAM', development_team, target_name)

            if provisioning_profile_uuid:
                pbx_project.set_flags(u'PROVISIONING_PROFILE', provisioning_profile_uuid, target_name)

            if code_sign_entitlements:
                pbx_project.set_flags(u'CODE_SIGN_ENTITLEMENTS', code_sign_entitlements, target_name)

            for target in pbx_project.objects.get_targets(target_name):
                pbx_project.objects[pbx_project.rootObject].set_provisioning_style(PBXProvioningTypes.MANUAL, target)

            pbx_project.save()
    def testConsistency(self):
        with open('samplescli/massive.pbxproj', 'r') as file:
            original = file.read()
            project = XcodeProject.load('samplescli/massive.pbxproj')
            saved = project.__repr__() + '\n'

            self.assertEqual(saved, original)
Beispiel #3
0
def start(pbxfile=None):
    project = XcodeProject.load(pbxfile)
    debugBuildFileUUIDs = fetchTargetBuildFileUUIDs(project, kDebugTarget)
    releaseBuildFileUUIDs = fetchTargetBuildFileUUIDs(project, kReleaseTarget)

    debugBuildFilesRefUUIDs = fetchFileRefUUIDSFromBuildFiles(
        project, debugBuildFileUUIDs)
    releaseBuildFilesRefUUIDs = fetchFileRefUUIDSFromBuildFiles(
        project, releaseBuildFileUUIDs)
    difference = set(debugBuildFilesRefUUIDs).difference(
        set(releaseBuildFilesRefUUIDs))

    for uuid in difference:
        fileRefUUIDs = fetchFileRefUUIDSFromBuildFiles(project,
                                                       [buildFileUUID])

    if len(difference):
        logForMissingFiles(project, difference)
        raise Exception, "❌❌ 请检查并补全上述缺失的文件(一般为Category忘记勾选)"
        # 看有没有必要自动添加了,安全起见还是报错手动添加
        # for buildFileUUID in debugBuildFileUUIDs:
        #     fileRefUUIDs = fetchFileRefUUIDSFromBuildFiles(project, [buildFileUUID])
        #     if len(fileRefUUIDs) <= 0:
        #         continue
        #     fileRefUUID = fileRefUUIDs[0]
        #     if fileRefUUID in difference:
        #         addTargetMembership(project, kReleaseTarget, buildFileUUID, fileRefUUID)
    project.save()
Beispiel #4
0
def create_models():
    """Start writing models into xcode project"""

    models_json = None
    model_folder = None
    model_group = None

    # Init Variables
    config = Config()

    model_json_path = config.json_path
    xcodeproj_path = config.xcproject_path
    model_folder = config.model_folder
    model_group = config.model_group

    with open(model_json_path, 'r') as json_file:
        models_json = json.load(json_file)

    proj = xc.load('%s/project.pbxproj' % (xcodeproj_path))
    backup = proj.backup()

    print "Preparing to edit project ..."
    print "Backup file = %s" % (backup)

    for key in models_json:
        model_json = models_json[key]
        createmodel(key, model_json, model_folder, model_group, proj)

    print "--- Writing to files finished with success! ---"
    print "--- Cleaning up ... ---"
    try:
        os.remove(backup)
    except OSError:
        pass
    print "--- Done ---"
Beispiel #5
0
 def set_resource_obfuscate_key(self, crypt_key):
     xcode_project_file_path = self._get_xcode_project_file_path(self.project_root)
     pbx_proj_file_path = os.path.join(xcode_project_file_path, "project.pbxproj")
     pbx_project = XcodeProject.load(pbx_proj_file_path)
     ios_app_target = self._get_ios_app_target(pbx_project)
     if ios_app_target:
         pbx_project.add_other_cflags('-DUSE_RESOURCE_OBFUSCATE -DRESOURCE_OBFUSCATE_KEY=%s' % crypt_key,
                                      ios_app_target.name)
def populateProject(projectfile, fileGroups, nodes):
    project = XcodeProject.load(projectfile)
    for node in nodes:
        groupName = node[0]
        entries = node[1]
        targets = node[2]
        addNode(project, groupName, entries, fileGroups, targets)
    project.save()
Beispiel #7
0
 def disable_versioning(self):
     """
     Deletes flags for automatic versioning.
     """
     project = XcodeProject.load(self.__path)
     project.remove_flags('CURRENT_PROJECT_VERSION', None)
     project.remove_flags('VERSIONING_SYSTEM', None)
     project.save()
def build_project(xcodeproj_path, pbxproj_path='project.pbxproj'):
    """
    call this initially. Will create the project object to work with.

    Args:
        xcodeproj_path -> the path to your xcodeproj file
        pbxproj_path -> the path to your pbxproj file (usually just project.pbxproj)
    """
    return XcodeProject.load(os.path.join(xcodeproj_path, pbxproj_path))
Beispiel #9
0
 def __init__(self, pbproject_path: str, target_name: str):
     self.pbproject_path = pbproject_path
     self.target_name = target_name
     self.project = XcodeProject.load(pbproject_path)
     self.build_configs = self.project.objects.get_configurations_on_targets(
         target_name=target_name)
     self.release_build_config = [
         b for b in self.build_configs if b.name == 'Release'
     ][-1]
Beispiel #10
0
def add_stickers_to_xcode():
    project = XcodeProject.load(f"{ios_root_folder}.xcodeproj/project.pbxproj")

    root_group = project.get_or_create_group(ios_folder_name)
    project.add_folder(f"{ios_root_folder}/Stickers",
                       parent=root_group,
                       file_options=FileOptions(ignore_unknown_type=True))

    project.save()
def patch_pbxproj(path, targets):
  project = XcodeProject.load(path)
  build_files = project.objects.get_objects_in_section('PBXBuildFile')
  for build_file in build_files:
    if 'fileRef' not in build_file:
      del project.objects[build_file.get_id()]
  for target in targets:
    project.add_flags('PRODUCT_MODULE_NAME', target, target)
  project.save()
 def initTestProject(self):
     # 初始化
     pbxproj=self.xcodeProjectRootPath+'/project_test.xcodeproj/project.pbxproj'
     infoPlistPath=self.xcodeProjectRootPath+'/project_test/Info.plist'
     self.project = XcodeProject.load(pbxproj)
     targetsNames=self.project.get_targets_names()
     for targetName in targetsNames:
         self.project.get_configSet_By_Target(targetName)
     print targetsNames
     pass
Beispiel #13
0
    def add_file(self, file_path, parent):
        pbx_project = XcodeProject.load(os.path.join(self.project_file_path, "project.pbxproj"))

        if parent is not None:
            parents = pbx_project.get_groups_by_name(parent)
            if parents is not None:
                parent = parents[0]

        pbx_project.add_file(file_path, parent)
        pbx_project.save()
def save_files_to_project(project_directory, internal_file_names, external_file_names):

	fileschanged = False
	projectName = ''
	searchDirectory = project_directory + '/../'
	for filepath in filter(lambda x: x.endswith('.xcodeproj'), os.listdir(searchDirectory)):
		projectName = filepath.partition('.')[0]

	project_file_path = project_directory +'../' + projectName + '.xcodeproj'
	backup_project_path = project_file_path + '-backup'

	print '1 - ' + project_directory
	print '2 - ' + project_file_path

	if os.path.exists(os.path.dirname(backup_project_path + '/')):
		shutil.rmtree(backup_project_path + '/')

	shutil.copytree(project_file_path, backup_project_path)

	project = XcodeProject.load(project_file_path + '/project.pbxproj')
	#backup_file = project.backup()

	parent_group = project.get_or_create_group(projectName)
	model_group = project.get_or_create_group('Model', parent=parent_group)
	mapping_group = project.get_or_create_group('Mapping', parent=model_group)
	internal_group = project.get_or_create_group('Internal', parent=model_group)

	#print('Project Name ' + projectName + ' Path ' + project_file_path)
	#print 'Backup File Name ' + backup_file

	for internal_name in internal_file_names:
		found_files = project.get_files_by_name(internal_name)
		if len(found_files) == 0:
			fileschanged = True
			internal_path = project_directory + '/Model/Internal/' + internal_name
			print '3 - ' + internal_path
			project.add_file(internal_path, parent=internal_group, force=False)

	for external_name in external_file_names:
		found_files = project.get_files_by_name(external_name)

		if len(found_files) == 0:
			fileschanged = True
			external_path = project_directory + '/Model/' + external_name
			print '4 - ' + external_path
			project.add_file(external_path, parent=model_group, force=False)

	if fileschanged:
		try:
			print('PROJECT SAVED')
			project.save()
		except:
			print('FAILED PROJECT SAVE')
		else:
			os.remove(backup_file)
Beispiel #15
0
    def __init__(self, project_path, config):
        self._project_dir = project_path
        self._config = Parser.load(config)
        self._project = XcodeProject.load(self._get_xcodeproj_path() +
                                          '/project.pbxproj')
        self._exclude = self._process_array(
            self._config.get('file', 'excludes').split(','))

        with open(self._get_info_plist_path(), 'rb') as fp:
            self._plist = plistlib.load(fp)
        self._start()
Beispiel #16
0
def init_viper(config_path: str, project_name: str, targets_list: List[str]):
    dir_path = os.path.dirname(os.path.realpath(__file__))
    common_dir = dir_path + '/Common'
    common_env = Environment(loader=FileSystemLoader(common_dir),
                             autoescape=select_autoescape(['.swift']))

    print('[INFO] Will use configuration file {}'.format(config_path))

    with open(config_path, 'r') as stream:
        yaml_data = yaml.load(stream)

    settings = yaml_data

    project = XcodeProject.load(project_name + '/project.pbxproj')
    print('[INFO] Using XCode project {}'.format(project_name))
    project_full_dir = os.path.dirname(
        os.path.realpath(project_name)) + '/' + settings['project_dir']

    project_common_dir = project_full_dir + '/ViperCommon'
    if not os.path.exists(project_common_dir):
        os.makedirs(project_common_dir)

    if 'targets' in settings:
        targets = settings['targets']

    # But this has higher priority
    if targets_list:
        targets = targets_list

    if 'base_viewcontroller' in settings:
        base_viewcontroller = settings['base_viewcontroller']
    else:
        base_viewcontroller = 'UIViewController'

    common_group = project.get_or_create_group('ViperCommon')
    for dirname, dirnames, filenames in os.walk(common_dir):
        for filename in filenames:
            template = common_env.get_template(filename)
            project_filename = os.path.join(project_common_dir, filename)
            rendered_template = template.render(
                base_viewcontroller=base_viewcontroller)
            output_file = open(project_filename, 'w')
            output_file.write(rendered_template)
            output_file.close()
            __add_to_project(project, project_filename, common_group, targets)

    for part in [
            'Views', 'Interactors', 'Presenters', 'Routers', 'ViewControllers'
    ]:
        part_dir_path = project_full_dir + '/' + part
        if not os.path.exists(part_dir_path):
            os.makedirs(part_dir_path)

    project.save()
Beispiel #17
0
    def add_generated_files_to_xcode_project(self, exec_code_file_path,
                                             auto_all_name, auto_all_function,
                                             xcode_project_path):
        """
        把生成的文件加入xcode工程
        :param generate_config:
        :param exec_code_file_path:
        :param auto_all_name:
        :param auto_all_function:
        :param xcode_project_path:
        :param group_name:
        :param search_path:
        :return:
        """
        group_name = self.generate_config["group_name"]

        search_path = self.generate_config["search_path"]

        # create action execute in repack
        insert_head_action = {
            "operation": "insert",
            "file_path": exec_code_file_path,
            "keys": self.generate_config["include_insert_keys"],
            "words": "\n#include \"%s.h\"\n" % auto_all_name
        }
        insert_code_action = {
            "operation": "insert",
            "file_path": exec_code_file_path,
            "keys": self.generate_config["code_insert_keys"],
            "words": "\n%s();\n" % auto_all_function
        }
        modify_exec_code_actions = {
            "name": "modify_files",
            "files": [insert_head_action, insert_code_action]
        }

        # add generated files to xcode project

        pbx_proj_file_path = os.path.join(
            self._get_xcode_project_file_path(xcode_project_path),
            "project.pbxproj")
        pbx_project = XcodeProject.load(pbx_proj_file_path)
        # add out dir to head search path
        pbx_project.add_header_search_paths(search_path)
        # add a group
        group = pbx_project.add_group(group_name)
        # add files
        for file_path in self.generated_files:
            print("===>add file %s to xcode" % (file_path))
            pbx_project.add_file(file_path, group)
        pbx_project.save()

        return modify_exec_code_actions
Beispiel #18
0
    def shuffle_compile_sources(self, target_name=None):
        pbx_project = XcodeProject.load(os.path.join(self.project_file_path, "project.pbxproj"))

        if target_name:
            target = pbx_project.get_target_by_name(target_name)
        else:
            target = self._get_ios_app_target(pbx_project)

        if target:

            # get sources build phase
            sources_build_phase = target.get_or_create_build_phase("PBXSourcesBuildPhase")
            if sources_build_phase:
                random.shuffle(sources_build_phase[0].files)
        pbx_project.save()
   def importmodelfiles():
   		instantiatorPath = output_directory + 'Internal/JMInstantiator.swift'
		instantiatorGenerator = InstantiatorGenerator(plistPaths, output_directory, version, testEnabled, jsonFormatEnabled)

		generate_file(instantiatorGenerator.internalGeneratedClass(), instantiatorPath, True)

        # open the project
		project = XcodeProject.load('myapp.xcodeproj/project.pbxproj')

		for mappingPath in plistPaths:
			classname = mappingPath[mappingPath.rindex('/',0,-1)+1:-1] if mappingPath.endswith('/') else mappingPath[mappingPath.rindex('/')+1:].split('.', 1 )[0]

			classGenerator = ClassGenerator(mappingPath, output_directory, version, testEnabled, jsonFormatEnabled)

			internalClassPath = output_directory + 'Internal/_'+ classname + '.swift'
			externalClassPath = output_directory + classname + '.swift'
Beispiel #20
0
    def enable_versioning(self, build_number: int = None):
        """
        This method adds missing flags for automatic versioning.
        With automatic versioning, project will be able to use
        agvtool.

        Keyword Arguments:
            build_number {int} -- Project build number which should be used.
                                  If not provided, it will be set to 1. (default: {None})
        """
        project = XcodeProject.load(self.__path)
        if build_number is None:
            build_number = 1
        project.set_flags('CURRENT_PROJECT_VERSION', str(build_number))
        project.set_flags('VERSIONING_SYSTEM', 'apple-generic')
        project.save()
Beispiel #21
0
def list_swift_files(project_path, target_name):
    """
    Lists Swift files for a target name.

    :param project_path: path to .xcodeproj file
    :param target_name: name of the target
    :return:
    """
    (project_directory, _) = os.path.split(project_path)
    project = XcodeProject.load(os.path.join(project_path, 'project.pbxproj'))
    target = project.get_target_by_name(target_name)

    build_phases = (project.objects[p] for p in target.buildPhases
                    if project.objects[p].isa == 'PBXSourcesBuildPhase')
    build_files = (f for p in build_phases for f in p.files)
    build_files = (project.objects[project.objects[f].fileRef]
                   for f in build_files)
    files = (__full_path(project, file) for file in build_files)
    return [os.path.join(project_directory, file_path) for file_path in files]
Beispiel #22
0
    def rename(self, target_name, package_id, display_name, new_project_file_name=None, product_name=None,
               new_scheme=None, old_scheme=None):
        if not new_project_file_name:
            new_project_file_name = target_name
        xcode_project_file_path = self.rename_xcode_project(new_project_file_name)

        # open pbx project
        pbx_proj_file_path = os.path.join(xcode_project_file_path, "project.pbxproj")
        pbx_project = XcodeProject.load(pbx_proj_file_path)
        self.rename_target(pbx_project, target_name, product_name)
        self.set_plist(pbx_project, package_id, display_name)
        ios_app_target = self._get_ios_app_target(pbx_project)
        if ios_app_target:
            for configuration in pbx_project.objects.get_configurations_on_targets(ios_app_target.name):
                print(configuration.buildSettings[u"PRODUCT_BUNDLE_IDENTIFIER"])
                if u"PRODUCT_BUNDLE_IDENTIFIER" in configuration.buildSettings:
                    configuration.set_flags(u"PRODUCT_BUNDLE_IDENTIFIER", package_id)
        pbx_project.save()

        self.rename_scheme(new_scheme if new_scheme else target_name, target_name, new_project_file_name, old_scheme)
Beispiel #23
0
def edit_unity_xcode_project(Log, unity_xcode_project_path, framework_path):
    # load unity iOS pbxproj project file
    unity_XcodeProject = XcodeProject.load(unity_xcode_project_path)

    frameworks = unity_XcodeProject.get_or_create_group('Frameworks')

    file_options_security_framework = FileOptions(embed_framework=False,
                                                  weak=True)
    unity_XcodeProject.add_file(framework_path + "Security.framework",
                                parent=frameworks,
                                tree='SDKROOT',
                                force=False,
                                file_options=file_options_security_framework)
    Log("added Security framework")

    # Add -ObjC to "Other Linker Flags" project settings.
    unity_XcodeProject.add_other_ldflags('-ObjC')

    # Save changes.
    unity_XcodeProject.save()
Beispiel #24
0
def main():
      inputs = docopt(__doc__)
      src_file = inputs["-f"]
      configration = inputs["-c"]
      raw_macros = inputs["-m"]
      headers = inputs["<header>"]
      
      project = XcodeProject.load(src_file)
      raw_macro_values = project.get_flags(u'GCC_PREPROCESSOR_DEFINITIONS', configuration_name=configration)
      
      macro_values = parse_macro_values(raw_macro_values)
      
      macros = raw_macros.split(",")

      values_to_transfer = {}
      for macro in macros:
            if macro in macro_values:
                  values_to_transfer[macro] = macro_values[macro]
      
      for header in headers: 
        write_header(header, values_to_transfer)
Beispiel #25
0
def main():
    if len(sys.argv) != 4:
        print(
            "Incorrect usage! {0} <xcodeproj_path> <target_name> <swiftlint_reference_file>"
            .format(sys.argv[0]))
        sys.exit(-1)

    xcodeproj_path = sys.argv[1]
    target_name = sys.argv[2]
    swiftlint_path = sys.argv[3]

    if os.path.isfile('.swiftlint.yml'):
        print("Script failed, found existing .swiftlint.yml file!")
        sys.exit(-1)

    with open(swiftlint_path, 'r') as sources:
        sources_config = yaml.load(sources)

        project = XcodeProject.load(
            os.path.join(xcodeproj_path, 'project.pbxproj'))
        files = list_files(project, target_name)

        with open('.swiftlint.yml', 'w') as output:
            sources_config['included'] = files
            yaml.dump(sources_config,
                      output,
                      default_flow_style=False,
                      allow_unicode=True)

            process = subprocess.run(["swiftlint"])

            try:
                os.remove('.swiftlint.yml')
            except OSError:
                print("Cleanup failed, could not remove .swiftlint.yml file")

            sys.exit(process.returncode)

    print("Script failed")
    sys.exit(-1)
Beispiel #26
0
def update_ios_project():
    def move_files_to_folder():
        for file in ui_group_files:
            base_path = f"./WAStickersThirdParty"

            if os.path.exists(f"{base_path}/{file.path}"
                              ) and not file.path.startswith("UI/"):
                os.rename(f"{base_path}/{file.path}",
                          f"{base_path}/UI/{file.path}")

        project.remove_group_by_id(ui_group.get_id())
        print(ui_group_files)

    def update_references():
        ui_group = project.get_or_create_group("UI", parent=root_group)
        base_path = f"./WAStickersThirdParty"

        for file in ui_group_files:
            if not file.path.startswith("UI/"):
                project.add_file(f"{base_path}/UI/{file.path}",
                                 parent=ui_group)
            else:
                project.add_file(f"{base_path}/{file.path}", parent=ui_group)

    project = XcodeProject.load(f"{ios_root_folder}.xcodeproj/project.pbxproj")

    root_group = project.get_or_create_group(ios_folder_name)

    ui_group = project.get_or_create_group("UI", parent=root_group)
    ui_group_files = [
        project.get_file_by_id(file_id) for file_id in ui_group.children
    ]

    move_files_to_folder()
    update_references()

    project.save()
Beispiel #27
0
            for build_file in project.get_build_files_for_file(file.get_id()):
                build_file.add_compiler_flags(flags)

excludes = [
    "^build$",
    "^CMakeLists.txt$",
    "^.DS_Store$",
    "^.*\.md$",
    "^.*\.js$",
    "^.*\.glsl$",
    "^.*\.sh$"
]

mainTargetName = "app-ios"

project = XcodeProject.load(f"{mainTargetName}.xcodeproj/project.pbxproj")

project_target = project.get_target_by_name(mainTargetName)

# required by Crashlytics
project.set_flags("DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym")

project.set_flags("GCC_ENABLE_CPP_EXCEPTIONS", "NO")
project.set_flags("GCC_ENABLE_CPP_RTTI", "NO")
project.set_flags("GCC_ENABLE_OBJC_EXCEPTIONS", "NO")
project.set_flags("GCC_OPTIMIZATION_LEVEL", "z", configuration_name='Release')
project.set_flags("LLVM_LTO", "YES", configuration_name='Release')

project_target.productName = proj_ios_name
project.set_flags("PRODUCT_BUNDLE_IDENTIFIER", application_id)
project.set_flags("IPHONEOS_DEPLOYMENT_TARGET", "12.0")
#!/usr/local/bin/python3
from pbxproj import XcodeProject
import json

jsonPath = "muxed.json"
with open(jsonPath) as f:
    conf = json.load(f)

project = XcodeProject.load(
    './repos/vidapp/vidtest/vidtest.xcodeproj/project.pbxproj')

mode = "Release"


def getflag(target, flag):
    for conf in project.objects.get_configurations_on_targets(target, mode):
        cdict = conf["buildSettings"]
        return cdict[flag]


def removeflag(target, flag):
    val = ""
    for conf in project.objects.get_configurations_on_targets(target, mode):
        cdict = conf["buildSettings"]
        val = cdict[flag]
    if val is None:
        return
    project.remove_flags(flag, val, target, "Debug")


l = "vidtest"
Beispiel #29
0
project.get_files_by_name
project.get_files_by_path

project.get_groups_by_name
project.get_groups_by_path

project.get_object(id)

object.get_id()
'''

config = {
'xcodeproj': './cloud-search.xcodeproj'
}
# open project
project = XcodeProject.load(config['xcodeproj'] + '/project.pbxproj')

class GroupStruct:
    Dict = {} # if an object has parrent, then it's content is it's parent
    def __init__(self, project):
        self.groups = project.objects.get_objects_in_section('PBXGroup')

        # initialize the dictionary of groups
        for item in self.groups:
            itemID = item.get_id().upper()
            for child in item.children:
                self.Dict[child.upper()] = itemID

    '''
        input: file id
        output: None if over maxIter, list of groups
Beispiel #30
0
    'Core/Services/StitchCoreRemoteMongoDBService',
    'Core/Services/StitchCoreTwilioService',
    'Darwin/StitchCore',
    'Darwin/Services/StitchAWSS3Service',
    'Darwin/Services/StitchAWSSESService',
    'Darwin/Services/StitchFCMService',
    'Darwin/Services/StitchHTTPService',
    'Darwin/Services/StitchLocalMongoDBService',
    'Darwin/Services/StitchRemoteMongoDBService',
    'Darwin/Services/StitchTwilioService',
]

# open the project
for module in modules:
    try:
        project = XcodeProject.load('{}/{}.xcodeproj/project.pbxproj'.format(
            module, os.path.basename(module)))

        frameworks = [
            os.path.abspath('Frameworks/ios/libbson.framework'),
            os.path.abspath('Frameworks/ios/libmongoc.framework'),
            os.path.abspath('Frameworks/ios/MongoSwift.framework')
        ]

        # add a file to it, force=false to not add it if it's already in the project
        options = FileOptions(create_build_files=True,
                              weak=True,
                              embed_framework=True,
                              code_sign_on_copy=True)

        for fmk in frameworks:
            project.add_file(fmk, force=False, file_options=options)
Beispiel #31
0
from pbxproj import XcodeProject
import sys
import os
import fnmatch

xcodeprojs = []
for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.xcodeproj'):  #project.pbxproj'):
        xcodeprojs.append(file)

if len(xcodeprojs) is 0:
    print(
        'No xcodeproj was found. Ensure you are running in the same directory as it.'
    )
    exit(1)

if len(xcodeprojs) > 1:
    print('Multiple xcodeproj found. Script will run on all of them.')

for xcodeproj in xcodeprojs:
    project = XcodeProject.load('{}/project.pbxproj'.format(xcodeproj))
    project.add_run_script(
        '"${PODS_ROOT}/SwiftLint/swiftlint" autocorrect; "${PODS_ROOT}/SwiftLint/swiftlint"',
        insert_before_compile=True)
    project.save()
Beispiel #32
0
def add_viper_files(config_path: str,
                    project_name: str,
                    module_name: str,
                    targets_list: List[str],
                    storyboard: str = None):
    with open(config_path, 'r') as stream:
        yaml_data = yaml.load(stream)

    settings = yaml_data

    project = XcodeProject.load(project_name + '/project.pbxproj')

    targets = []

    if 'targets' in settings:
        targets = settings['targets']

    # But this has higher priority
    if targets_list:
        targets = targets_list

    if storyboard:
        storyboard_name = storyboard
    else:
        storyboard_name = 'Main'

    today = datetime.date.today()
    today_str = today.strftime('%d.%m.%y')
    year_str = today.strftime('%Y')

    template_dir = settings['templates_dir']
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if template_dir == '$TEMPLATES':
        template_dir = dir_path + '/Templates'

    project_full_dir = os.path.dirname(
        os.path.realpath(project_name)) + '/' + settings['project_dir']

    templates_env = Environment(loader=FileSystemLoader(template_dir),
                                autoescape=select_autoescape(['.tpl.swift']))

    parts = {
        'View': 'Views',
        'Interactor': 'Interactors',
        'Presenter': 'Presenters',
        'Router': 'Routers',
        'Controller': 'ViewControllers'
    }

    for key in parts.keys():
        try:
            template = templates_env.get_template(key + '.tpl.swift')
        except exceptions.TemplateNotFound:
            print(Fore.RED +
                  'Cannot find template {0}'.format(key + '.tpl.swift'))
            print(Style.RESET_ALL)
            sys.exit(0)

        filename = '{2}/{3}/{1}{0}.swift'.format(key, module_name,
                                                 project_full_dir, parts[key])
        rendered_template = template.render(module_name=module_name,
                                            file_type=key,
                                            creation_date=today_str,
                                            creation_year=year_str,
                                            storyboard_name=storyboard_name,
                                            project_author=settings['author'])

        try:
            output_file = open(filename, 'w')
            output_file.write(rendered_template)
            output_file.close()
        except FileNotFoundError:
            print(Fore.RED +
                  'Cannot find file {0}; try to use `swivigen init`'.format(
                      filename))
            print(Style.RESET_ALL)
            sys.exit(0)

        if key == 'Controller':
            project_group = project.get_or_create_group(
                settings['uikit_controllers_group'])
        else:
            project_group = project.get_or_create_group('{0}s'.format(key))
        __add_to_project(project, filename, project_group, targets)

    project.save()