Files

81 lines
4.5 KiB
Python

import json
import shutil
import zipfile
from pathlib import Path
from .storage import workspace, task_dir, inside, digest, write
from .eda import verify_native
from .step_colors import validate_step_colors
from .native_policy import DESIGN_POLICY
from .checks import VALIDATION_POLICY
REQUIRED = {'project','schematic','layout','step','render'}
def inspect(path, kind):
data = path.read_bytes()
if len(data)<100:
raise ValueError(f'{kind}: file is empty or too small')
ext = path.suffix.lower()
warnings=[]
if kind == 'step':
if ext not in {'.stp','.step'} or not data.lstrip().startswith(b'ISO-10303-21;') or b'END-ISO-10303-21;' not in data or b'CARTESIAN_POINT' not in data or b'SHAPE_REPRESENTATION' not in data:
raise ValueError('STEP must be an extracted, real ISO10303 model')
try:
validate_step_colors(data)
except ValueError as exc:
warnings.append({'type':'warning','code':'STEP_APPEARANCE','message':str(exc)})
elif kind == 'project':
if ext not in {'.epro','.epro2','.zip'}:
raise ValueError('Editable native EasyEDA project required')
if zipfile.is_zipfile(path):
with zipfile.ZipFile(path) as z:
if not z.namelist() or z.testzip():
raise ValueError('Invalid native project archive')
elif b'DOCHEAD' not in data and not data.lstrip().startswith(b'{'):
raise ValueError('Unrecognized native project')
elif kind in {'render','schematic','layout'}:
png = data.startswith(b'\x89PNG\r\n\x1a\n')
jpg = data.startswith(b'\xff\xd8\xff')
pdf = data.startswith(b'%PDF')
svg = b'<svg' in data[:2000]
if not (png or jpg or (kind != 'render' and (pdf or svg))):
raise ValueError(f'{kind}: native preview or real render required')
return {'bytes':len(data),'sha256':digest(data),'warnings':warnings}
async def deliver(t, args):
files=args['files']
# Run the same gate as pcb_check before any packaging work.
verification=await verify_native(t,args['schematic_id'],args['pcb_id'])
if not REQUIRED <= {f['kind'] for f in files}:
raise ValueError('Missing required deliverables: '+', '.join(sorted(REQUIRED-{f['kind'] for f in files})))
checked=[]
for f in files:
path=inside(workspace(t),f['path'])
if not path.is_file() or path.is_symlink():
raise ValueError('Missing artifact: '+f['path'])
checked.append({**f,**inspect(path,f['kind']),'source':path})
folder=task_dir(t['id'])/'delivery'
folder.mkdir(exist_ok=True)
entries=[]
for index,f in enumerate(checked):
name=f'{index+1:02d}-{f["source"].name}'
target=folder/name
shutil.copyfile(f['source'],target)
# Recheck after copy: agent may still be doing work in the same filesystem.
if digest(target.read_bytes()) != f['sha256']:
raise ValueError('Artifact changed during delivery')
entries.append({'name':name,'kind':f['kind'],'label':f.get('label') or f['source'].name,'bytes':f['bytes'],'sha256':f['sha256'],'warnings':f['warnings']})
manifest={'task_id':t['id'],'thread_id':t['thread_id'],'approval':t['approval'],'source_hash':t['frozen_source'],'verification':verification,'files':entries,'notes':args['notes']}
manifest.update(design_policy=DESIGN_POLICY, source_migrations=t.get('source_migrations',[]), acceptance_run_invalidated=t.get('acceptance_run_invalidated',False))
warnings=[{'scope':scope,'diagnostic':w} for scope,items in verification['warnings'].items() for w in items]
warnings += [{'scope':f['name'],'diagnostic':w} for f in entries for w in f['warnings']]
manifest.update(validation_policy=VALIDATION_POLICY,warnings=warnings)
write(folder/'manifest.json',manifest)
shutil.copyfile(task_dir(t['id'])/'native-verification.json',folder/'native-verification.json')
bundle=folder/'delivery.zip'
with zipfile.ZipFile(bundle,'w',zipfile.ZIP_DEFLATED) as z:
# Never include stale files left by an earlier submission attempt.
for name in [f['name'] for f in entries]+['manifest.json','native-verification.json']:
z.write(folder/name,name)
entries.append({'name':bundle.name,'kind':'bundle','label':'完整交付包','bytes':bundle.stat().st_size,'sha256':digest(bundle.read_bytes())})
return {'files':entries,'verification':verification,'warnings':warnings,'validation_policy':VALIDATION_POLICY,'notes':args['notes'],'schematic_id':verification['schematic_id'],'pcb_id':verification['pcb_id']}