#!/usr/bin/env python3 """Single-install Release delivery; keeps a product lock through host acceptance.""" from pathlib import Path import subprocess,os,json,shutil,plistlib,uuid,sys,datetime,hashlib,time ROOT=Path(__file__).resolve().parent.parent CACHE=Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color') LOCK=Path('/Users/mac/.codex/app-delivery-locks/com.dayu.color.lock') DEST=Path('/Library/Plug-Ins/FxPlug/大鱼调色.app') APP=CACHE/'DerivedData/Build/Products/Release/大鱼调色.app' LOOSE=CACHE/'DerivedData/Build/Products/Release/大鱼调色 XPC Service.pluginkit' PLUGIN='Contents/PlugIns/大鱼调色 XPC Service.pluginkit' TEMPLATE=Path.home()/'Movies/Motion Templates.localized/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef' IDENTITY='Developer ID Application: zhong luo (B3W25FX5H5)' PROFILE='codex-dayu-notary-B3W25FX5H5' KEYCHAIN='/Users/mac/Library/Keychains/login.keychain-db' def run(*args,log=None): if log: with Path(log).open('w') as f:subprocess.run(args,cwd=ROOT,stdout=f,stderr=subprocess.STDOUT,check=True) return '' return subprocess.check_output(args,cwd=ROOT,text=True,stderr=subprocess.STDOUT).strip() def hosts_closed(wait=False): announced=False while True: lines=run('ps','-axo','pid=,comm=').splitlines() live=[l for l in lines if l.endswith(('/Contents/MacOS/Final Cut Pro','/Contents/MacOS/Motion'))] if not live:return if not wait:raise RuntimeError('请先正常退出宿主,再继续交付:'+str(live)) if not announced:print('Notarized APP retained; waiting for the host to save and quit normally before replacement.',flush=True);announced=True time.sleep(1) def identity(path,expected): p=plistlib.loads((path/'Contents/Info.plist').read_bytes()) if p['CFBundleIdentifier']!=expected:raise RuntimeError('产品身份不匹配: '+str(path)) def unregister(path): reg=run('pluginkit','-m','-A','-D','-v','-i','com.dayu.color.XPC') if any(l.rstrip().endswith('\t'+str(path)) for l in reg.splitlines()):run('pluginkit','-r',str(path)) def self_test(executable,report): result=subprocess.run([str(executable),'--self-test'],cwd=ROOT,text=True,capture_output=True,env=dict(os.environ,DY_DIAGNOSTIC_FACE_FIXTURE=str(ROOT/'tools/fixtures/astronaut.png'))) report.write_text(result.stdout) report.with_suffix('.stderr').write_text(result.stderr) try:parsed=json.loads(result.stdout) except json.JSONDecodeError:raise RuntimeError('原生自检未返回有效结果,诊断已保留:'+str(report)) if result.returncode or not parsed.get('pass'): failed=[x.get('name') for x in parsed.get('results',[]) if not x.get('pass',True)] raise RuntimeError('原生自检未通过,正式旧版未替换。诊断:'+str(report)+';失败项:'+str(failed)) return parsed def main(): hosts_closed();CACHE.mkdir(parents=True,exist_ok=True);LOCK.parent.mkdir(parents=True,exist_ok=True);LOCK.mkdir() (LOCK/'owner.json').write_text(json.dumps(dict(PID=os.getpid(),cwd=str(ROOT),product='大鱼调色',started=datetime.datetime.now(datetime.timezone.utc).isoformat()))) old=None;stage=None try: ids=run('security','find-identity','-v','-p','codesigning') if IDENTITY not in ids:raise RuntimeError('有效发布证书或私钥不可用') if any(l.endswith('/Contents/MacOS/大鱼调色') for l in run('ps','-axo','comm=').splitlines()):raise RuntimeError('请先正常退出当前大鱼调色窗口') print('Building final Release',flush=True) run('xcodebuild','-project','大鱼调色.xcodeproj','-scheme','Wrapper Application','-configuration','Release','-enableAddressSanitizer','NO','-derivedDataPath',str(CACHE/'DerivedData'),'clean','build',log=CACHE/'release-build.log') b=APP/'Contents/Resources/FCP Templates/大鱼调色.moef';b.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(ROOT/'template/大鱼调色.moef',b) b.chmod(0o644) for name in ['large.png','small.png']: if (ROOT/'template'/name).exists(): target=b.parent/name;shutil.copy2(ROOT/'template'/name,target);target.chmod(0o644) # Sources on exFAT can be exposed as owner-only. Installer changes ownership to root. (APP/'Contents/Resources/Basis_balanceWheel.png').chmod(0o644) identity(APP,'com.dayu.color');plugin=APP/PLUGIN;identity(plugin,'com.dayu.color.XPC') # Xcode registers its build product with Launch Services. Keep the host from # discovering this generated copy while signing/notarization are pending. unregister(plugin);unregister(LOOSE) for name in ['FxPlug','PluginManager']:run('codesign','--force','--timestamp','--options','runtime','--sign',IDENTITY,str(plugin/'Contents/Frameworks'/(name+'.framework'))) run('codesign','--force','--timestamp','--options','runtime','--sign',IDENTITY,str(plugin)) run('codesign','--force','--timestamp','--options','runtime','--entitlements',str(ROOT/'大鱼调色/Wrapper Application/SandboxEntitlements.entitlements'),'--sign',IDENTITY,str(APP)) run('codesign','--verify','--deep','--strict',str(APP)) details=run('codesign','-dvvv',str(APP)) if 'TeamIdentifier=B3W25FX5H5' not in details or 'Timestamp=' not in details or 'runtime' not in details:raise RuntimeError('签名身份/时间戳/runtime未通过') preflight=self_test(plugin/'Contents/MacOS/大鱼调色 XPC Service',CACHE/'release-preflight.json') (CACHE/'release-preflight.json').write_text(json.dumps(preflight,ensure_ascii=False,indent=2)+'\n') if not preflight.get('pass'):raise RuntimeError('Release集成自检失败,正式旧版未替换') archive=CACHE/'notarization-submission.zip' if archive.exists():archive.unlink() run('ditto','-c','-k','--keepParent',str(APP),str(archive));print('Submitting signed Release to Apple',flush=True) result=json.loads(run('xcrun','notarytool','submit',str(archive),'--keychain-profile',PROFILE,'--keychain',KEYCHAIN,'--wait','--output-format','json'));(CACHE/'notary-result.json').write_text(json.dumps(result,indent=2)) if result.get('status')!='Accepted': if result.get('id'):run('xcrun','notarytool','log',result['id'],'--keychain-profile',PROFILE,'--keychain',KEYCHAIN,str(CACHE/'notary-rejection.json')) raise RuntimeError('Apple未Accepted,正式旧版未替换') run('xcrun','stapler','staple',str(APP));run('xcrun','stapler','validate',str(APP));hosts_closed(wait=True) stage=DEST.parent/('.dayu-color-staging-'+uuid.uuid4().hex+'.app');run('ditto',str(APP),str(stage)) if DEST.exists(): identity(DEST,'com.dayu.color');old=DEST.parent/('.dayu-color-previous-'+uuid.uuid4().hex+'.app');os.replace(DEST,old) os.replace(stage,DEST);stage=None try: identity(DEST,'com.dayu.color');run('codesign','--verify','--deep','--strict',str(DEST));run('xcrun','stapler','validate',str(DEST));gate=run('spctl','--assess','--type','execute','--verbose=2',str(DEST)) installedTest=self_test(DEST/PLUGIN/'Contents/MacOS/大鱼调色 XPC Service',CACHE/'installed-self-test.json') if not installedTest.get('pass'):raise RuntimeError('正式安装版原生集成自检失败') (ROOT/'verification/InstalledSelfTest.json').write_text(json.dumps(installedTest,ensure_ascii=False,indent=2)+'\n') run('open',str(DEST)) for attempt in range(20): if str(DEST/'Contents/MacOS/大鱼调色') in run('ps','-axo','comm=').splitlines():break time.sleep(.25) else:raise RuntimeError('未从正式安装路径启动') except Exception: failed=DEST.parent/('.dayu-color-failed-'+uuid.uuid4().hex+'.app');os.replace(DEST,failed) if old:os.replace(old,DEST);old=None raise TEMPLATE.parent.mkdir(parents=True,exist_ok=True) if TEMPLATE.exists():shutil.copy2(TEMPLATE,CACHE/'previous-template.moef') tmp=TEMPLATE.with_name('.dayu-color-template-stage.moef');shutil.copy2(DEST/'Contents/Resources/FCP Templates/大鱼调色.moef',tmp);os.replace(tmp,TEMPLATE) for name in ['large.png','small.png']: source=DEST/'Contents/Resources/FCP Templates'/name;target=TEMPLATE.parent/name if source.exists(): if target.exists():os.chflags(target,0) shutil.copy2(source,target);os.chflags(target,2) # All generated copies are removed before final registry/host verification. for copy,expected in [(APP,'com.dayu.color'),(LOOSE,'com.dayu.color.XPC')]: if copy.exists():identity(copy,expected);unregister(copy/PLUGIN if copy.suffix=='.app' else copy);shutil.rmtree(copy) if old:unregister(old/PLUGIN) archive.unlink();backup=CACHE/'previous-template.moef' if backup.exists():backup.unlink() # Unregistering an old copy can race the host's launch registration. Re-add # only the verified installed path; never repeat signing/notarization/install. for attempt in range(3): run('pluginkit','-a',str(DEST/PLUGIN));registry=run('pluginkit','-m','-A','-D','-v','-i','com.dayu.color.XPC') entries=[l for l in registry.splitlines() if 'com.dayu.color.XPC(' in l] if entries:break time.sleep(.5) if len(entries)!=1 or not entries[0].rstrip().endswith('\t'+str(DEST/PLUGIN)):raise RuntimeError('PluginKit发现多份/错误版本: '+registry) record=dict(status='installed-awaiting-host-verification',path=str(DEST),bundleID='com.dayu.color',version=plistlib.loads((DEST/'Contents/Info.plist').read_bytes())['CFBundleShortVersionString'],build=plistlib.loads((DEST/'Contents/Info.plist').read_bytes())['CFBundleVersion'],team='B3W25FX5H5',notaryID=result['id'],notaryStatus=result['status'],gatekeeper=gate,sourceCommit=run('git','rev-parse','HEAD'),templatePath=str(TEMPLATE),templateSHA256=hashlib.sha256(TEMPLATE.read_bytes()).hexdigest(),shaderSHA256=hashlib.sha256((DEST/PLUGIN/'Contents/Resources/default.metallib').read_bytes()).hexdigest()) if old:record['previousInstallBackup']=str(old) output=ROOT/'verification/Delivery.json';output.write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n') run('open',str(DEST));print('FORMAL_INSTALLED. Run installed self-test and host verification; type complete only after success. Type leave to preserve pending state.',flush=True) for decision in sys.stdin: if decision.strip()=='complete': if old and old.exists():identity(old,'com.dayu.color');unregister(old/PLUGIN);shutil.rmtree(old);old=None record.pop('previousInstallBackup',None);record['status']='verified';output.write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n');break if decision.strip()=='leave':break finally: if stage and stage.exists():shutil.rmtree(stage) (LOCK/'owner.json').unlink();LOCK.rmdir() if __name__=='__main__':main()