Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / generate-mobile-project.py

Raw 9.4 KB on 0e4fe45e403a1b6b5a57aa68addd681995d37722
1#!/usr/bin/env python3
2"""Generate an independent iPhone/iPad target without modifying other platforms."""
3from pathlib import Path
4import hashlib
5import json
6from xcode_zipfoundation import add_zipfoundation
7
8root = Path(__file__).resolve().parents[1]
9objects = {}
10def obj(label, isa, **values):
11 key = hashlib.sha256(label.encode()).hexdigest()[:24].upper()
12 objects[key] = dict(isa=isa, **values)
13 return key
14def ref(path, kind):
15 return obj('file:' + path, 'PBXFileReference', lastKnownFileType=kind, path=path, sourceTree='<group>')
16def build(key): return obj('build:' + key, 'PBXBuildFile', fileRef=key)
17shared = ['CloudSyncLedger', 'CloudProjectPackage', 'CloudSyncAppData', 'CloudSyncService', 'CloudSyncView', 'UserBackup', 'UserBackupZIP', 'UserBackupView', 'PulseCanvasOnboarding', 'VisualizerFavoriteGesture', 'VisualPreset', 'VisualPalette', 'OriginalGeometry', 'NativeEffects', 'ProjectMPresets', 'StrobeDetector',
18 'VisualizerRenderer', 'AudioAnalysis', 'StudioTimeline', 'VisualizerPoolControls', 'RadioLibrary', 'StudioMusicPicker',
19 'StudioStore', 'SocialExportController', 'SecurityScopedAccess', 'AudioController', 'RadioController', 'BundledSoundtrack']
20sources = ['Sources/PulseCanvas/' + name + '.swift' for name in shared] + ['macOS/BundleResources.swift']
21sources += sorted(str(p.relative_to(root)) for p in (root / 'mobile').glob('*.swift'))
22source_refs = [ref(p, 'sourcecode.swift') for p in sources]
23resources = [ref('Localization/Localizable.xcstrings', 'text.json.xcstrings'), ref('Sources/PulseCanvas/Resources/Onboarding', 'folder'), ref('mobile/Assets.xcassets', 'folder.assetcatalog'), ref('.build/mobile-resources/NativeAssets', 'folder'), ref('.build/mobile-resources/Legal', 'folder'),
24 ref('macOS/PrivacyInfo.xcprivacy', 'text.xml')]
25config = ref('mobile/Release.xcconfig', 'text.xcconfig')
26info = ref('mobile/Info.plist', 'text.plist.xml')
27product = obj('product', 'PBXFileReference', explicitFileType='wrapper.application', path='PulseCanvas Mobile.app', sourceTree='BUILT_PRODUCTS_DIR')
28# UI tests (mobile/UITests): a separate bundle that drives the real app through its launch hooks (VisionLaunchOptions)
29ui_sources = sorted(str(p.relative_to(root)) for p in (root / 'mobile/UITests').glob('*.swift'))
30ui_refs = [ref(p, 'sourcecode.swift') for p in ui_sources]
31ui_product = obj('uitests-product', 'PBXFileReference', explicitFileType='wrapper.cfbundle', path='PulseCanvasMobileUITests.xctest', sourceTree='BUILT_PRODUCTS_DIR')
32products = obj('products', 'PBXGroup', children=[product, ui_product], name='Products', sourceTree='<group>')
33group = obj('main', 'PBXGroup', children=source_refs + ui_refs + resources + [ref('Version.xcconfig', 'text.xcconfig'), config, info, products], sourceTree='<group>')
34prepare = obj('prepare', 'PBXShellScriptBuildPhase', buildActionMask=2147483647, files=[], inputPaths=[], outputPaths=[],
35 runOnlyForDeploymentPostprocessing=0, shellPath='/bin/bash', shellScript='"$SRCROOT/scripts/prepare-mobile-resources.sh"\n',
36 name='Prepare native Metal resources only', alwaysOutOfDate=1)
37def phase(label, isa, files): return obj(label, isa, buildActionMask=2147483647, files=files, runOnlyForDeploymentPostprocessing=0)
38phases = [prepare, phase('sources', 'PBXSourcesBuildPhase', [build(k) for k in source_refs]),
39 phase('frameworks', 'PBXFrameworksBuildPhase', []), phase('resources', 'PBXResourcesBuildPhase', [build(k) for k in resources])]
40def configurations(label, target=False):
41 keys = []
42 for name in ['Debug', 'Release']:
43 values = dict(SDKROOT='iphoneos', CLANG_ENABLE_MODULES='YES')
44 if target: values.update(SWIFT_OPTIMIZATION_LEVEL='-Onone' if name == 'Debug' else '-O', SWIFT_EMIT_LOC_STRINGS='NO', SWIFT_ACTIVE_COMPILATION_CONDITIONS='$(inherited) DEBUG' if name == 'Debug' else '$(inherited)')
45 keys.append(obj(label + name, 'XCBuildConfiguration', buildSettings=values, name=name,
46 **({'baseConfigurationReference': config} if target else {})))
47 return obj(label + 'list', 'XCConfigurationList', buildConfigurations=keys, defaultConfigurationIsVisible=0, defaultConfigurationName='Release')
48target = obj('target', 'PBXNativeTarget', buildConfigurationList=configurations('targetConfig', True), buildPhases=phases,
49 buildRules=[], dependencies=[], name='PulseCanvasMobile', productName='PulseCanvas Mobile', productReference=product,
50 productType='com.apple.product-type.application')
51def ui_configurations():
52 keys = []
53 for name in ['Debug', 'Release']:
54 values = dict(SDKROOT='iphoneos', SUPPORTED_PLATFORMS='iphoneos iphonesimulator', TARGETED_DEVICE_FAMILY='1,2', IPHONEOS_DEPLOYMENT_TARGET='18.0',
55 SWIFT_VERSION='5.0', CLANG_ENABLE_MODULES='YES', GENERATE_INFOPLIST_FILE='YES', CODE_SIGN_STYLE='Automatic',
56 DEVELOPMENT_TEAM='22HV69L32T', PRODUCT_BUNDLE_IDENTIFIER='com.protomota.pulsecanvas.mobile.uitests',
57 PRODUCT_NAME='PulseCanvasMobileUITests', TEST_TARGET_NAME='PulseCanvasMobile',
58 SWIFT_OPTIMIZATION_LEVEL='-Onone' if name == 'Debug' else '-O')
59 keys.append(obj('uitestsConfig' + name, 'XCBuildConfiguration', buildSettings=values, name=name))
60 return obj('uitestsConfiglist', 'XCConfigurationList', buildConfigurations=keys, defaultConfigurationIsVisible=0, defaultConfigurationName='Debug')
61project_key = hashlib.sha256(b'project').hexdigest()[:24].upper() # obj('project', ...) below gets this key
62proxy = obj('uitests-proxy', 'PBXContainerItemProxy', containerPortal=project_key, proxyType=1, remoteGlobalIDString=target, remoteInfo='PulseCanvasMobile')
63ui_target = obj('uitests-target', 'PBXNativeTarget', buildConfigurationList=ui_configurations(),
64 buildPhases=[phase('uitests-sources', 'PBXSourcesBuildPhase', [build(k) for k in ui_refs]),
65 phase('uitests-frameworks', 'PBXFrameworksBuildPhase', []), phase('uitests-resources', 'PBXResourcesBuildPhase', [])],
66 buildRules=[], dependencies=[obj('uitests-dependency', 'PBXTargetDependency', target=target, targetProxy=proxy)],
67 name='PulseCanvasMobileUITests', productName='PulseCanvasMobileUITests', productReference=ui_product,
68 productType='com.apple.product-type.bundle.ui-testing')
69project = obj('project', 'PBXProject', attributes={'LastUpgradeCheck': '2700', 'TargetAttributes': {target: {'SystemCapabilities': {'com.apple.iCloud': {'enabled': 1}}}, ui_target: {'TestTargetID': target}}}, buildConfigurationList=configurations('projectConfig'),
70 compatibilityVersion='Xcode 14.0', developmentRegion='en', hasScannedForEncodings=0, knownRegions=['en', 'Base'],
71 mainGroup=group, productRefGroup=products, projectDirPath='', projectRoot='', targets=[target, ui_target])
72assert project == project_key
73add_zipfoundation(objects, obj, target, project)
74def encode(value, level=0):
75 if isinstance(value, dict):
76 return '{\n' + ''.join('\t' * (level + 1) + json.dumps(k) + ' = ' + encode(v, level + 1) + ';\n' for k, v in value.items()) + '\t' * level + '}'
77 if isinstance(value, list): return '(\n' + ''.join('\t' * (level + 1) + encode(v, level + 1) + ',\n' for v in value) + '\t' * level + ')'
78 return str(value) if isinstance(value, int) else json.dumps(value)
79folder = root / 'PulseCanvasMobile.xcodeproj'
80folder.mkdir(exist_ok=True)
81(folder / 'project.pbxproj').write_text('// !$*UTF8*$!\n' + encode(dict(archiveVersion=1, classes={}, objectVersion=56, objects=objects, rootObject=project)) + '\n')
82scheme = folder / 'xcshareddata/xcschemes/PulseCanvasMobile.xcscheme'
83scheme.parent.mkdir(parents=True, exist_ok=True)
84reference = f'<BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="{target}" BuildableName="PulseCanvas Mobile.app" BlueprintName="PulseCanvasMobile" ReferencedContainer="container:PulseCanvasMobile.xcodeproj"/>'
85ui_reference = f'<BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="{ui_target}" BuildableName="PulseCanvasMobileUITests.xctest" BlueprintName="PulseCanvasMobileUITests" ReferencedContainer="container:PulseCanvasMobile.xcodeproj"/>'
86scheme.write_text(f'''<?xml version="1.0" encoding="UTF-8"?>
87<Scheme LastUpgradeVersion="2700" version="1.3">
88 <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"><BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">{reference}</BuildActionEntry></BuildActionEntries></BuildAction>
89 <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="YES"><Testables><TestableReference skipped="NO">{ui_reference}</TestableReference></Testables></TestAction>
90 <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" allowLocationSimulation="YES"><BuildableProductRunnable runnableDebuggingMode="0">{reference}</BuildableProductRunnable></LaunchAction>
91 <ProfileAction buildConfiguration="Release"><BuildableProductRunnable runnableDebuggingMode="0">{reference}</BuildableProductRunnable></ProfileAction>
92 <AnalyzeAction buildConfiguration="Debug"/>
93 <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
94</Scheme>
95''')
96print(folder)