137 lines
6.7 KiB
Python
137 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Local build and unit-test handoff; Python 3.7+, standard library only.
|
|
|
|
Never installs packages, starts the live GUI, changes a domain or qualifies a
|
|
release. Reports contain build output and package observations, not projects.
|
|
"""
|
|
import argparse
|
|
import datetime
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shlex
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def utc_now():
|
|
return datetime.datetime.now(datetime.timezone.utc).isoformat()
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--jobs', type=int, default=2, choices=range(1, 9))
|
|
parser.add_argument('--build-dir', default='build-astra')
|
|
args = parser.parse_args()
|
|
if os.geteuid() == 0:
|
|
print('Запускайте сборку обычным пользователем, без sudo.', file=sys.stderr)
|
|
return 77
|
|
|
|
os.umask(0o077)
|
|
build = (ROOT / args.build_dir).resolve()
|
|
# Restrict generated build files to a separate, ignored directory.
|
|
if build.parent != ROOT or not build.name.startswith('build-'):
|
|
parser.error('--build-dir должен быть отдельным каталогом build-* в корне исходников')
|
|
destination = ROOT / 'artifacts' / 'astra-lab'
|
|
destination.mkdir(parents=True, exist_ok=True)
|
|
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ-')
|
|
report_dir = Path(tempfile.mkdtemp(prefix=stamp, dir=str(destination)))
|
|
report = dict(schema_version=1, started_at=utc_now(), finished_at=None,
|
|
scope='LOCAL_BUILD_AND_UNIT_TESTS_ONLY', release_validated=False,
|
|
status='RUNNING', build_directory=str(build), steps=[])
|
|
source_hash = hashlib.sha256()
|
|
sources = [ROOT / 'CMakeLists.txt']
|
|
for directory in ('src', 'schemas', 'data', 'resources', 'tests/unit', 'tools'):
|
|
sources.extend(p for p in (ROOT / directory).rglob('*')
|
|
if p.is_file() and '__pycache__' not in p.parts and p.suffix != '.pyc')
|
|
for path in sorted(sources):
|
|
source_hash.update(path.relative_to(ROOT).as_posix().encode('utf-8') + b'\0')
|
|
source_hash.update(path.read_bytes())
|
|
report['source_digest'] = source_hash.hexdigest()
|
|
|
|
def run(name, argv, cwd=ROOT, env=None):
|
|
print('\n{}: {}'.format(name, ' '.join(shlex.quote(str(a)) for a in argv)), flush=True)
|
|
step = dict(name=name, argv=[str(a) for a in argv], cwd=str(cwd),
|
|
started_at=utc_now(), status='RUNNING', log=name + '.log')
|
|
report['steps'].append(step)
|
|
try:
|
|
with (report_dir / step['log']).open('w', encoding='utf-8') as log:
|
|
with subprocess.Popen(argv, cwd=str(cwd), env=env, stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, universal_newlines=True,
|
|
encoding='utf-8', errors='replace') as process:
|
|
try:
|
|
for line in process.stdout:
|
|
print(line, end='', flush=True)
|
|
log.write(line)
|
|
code = process.wait()
|
|
except KeyboardInterrupt:
|
|
process.terminate()
|
|
process.wait()
|
|
raise
|
|
step['exit_code'] = code
|
|
if code:
|
|
raise RuntimeError('Этап {} завершился с кодом {}. См. {}'.format(name, code, step['log']))
|
|
step['status'] = 'PASS'
|
|
except (OSError, RuntimeError, KeyboardInterrupt) as error:
|
|
step['status'] = 'INTERRUPTED' if isinstance(error, KeyboardInterrupt) else 'FAIL'
|
|
step['error'] = str(error)
|
|
raise
|
|
finally:
|
|
step['finished_at'] = utc_now()
|
|
|
|
code = 1
|
|
try:
|
|
# Save observations even when Qt/CMake are absent; never edit the release lock.
|
|
run('environment', [sys.executable, str(ROOT / 'tools/collect_compatibility.py'),
|
|
'--output', str(report_dir / 'environment.json')])
|
|
missing = [name for name in ('cmake', 'ctest', 'g++', 'make') if not shutil.which(name)]
|
|
if missing:
|
|
raise RuntimeError('Не найдены инструменты: {}. Порядок подготовки: docs/astra-lab.ru.md'.format(', '.join(missing)))
|
|
run('configure', ['cmake', '-S', str(ROOT), '-B', str(build), '-G', 'Unix Makefiles',
|
|
'-DCMAKE_BUILD_TYPE=Debug', '-DCMAKE_INSTALL_PREFIX=/usr',
|
|
'-DBUILD_TESTING=ON', '-DALD_CORE_ONLY=OFF'])
|
|
run('build', ['cmake', '--build', str(build), '--parallel', str(args.jobs)])
|
|
environment = os.environ.copy()
|
|
environment['QT_QPA_PLATFORM'] = 'offscreen'
|
|
# ctest --test-dir is newer than the project's CMake 3.13 baseline.
|
|
run('ctest', ['ctest', '--output-on-failure', '--timeout', '120'], cwd=build, env=environment)
|
|
report['binaries'] = []
|
|
for name in ('ald-transition-console', 'ald-transition-executor'):
|
|
binary = build / name
|
|
report['binaries'].append(dict(name=name, size=binary.stat().st_size,
|
|
sha256=hashlib.sha256(binary.read_bytes()).hexdigest()))
|
|
report['status'] = 'PASS'
|
|
code = 0
|
|
except KeyboardInterrupt:
|
|
report['status'] = 'INTERRUPTED'
|
|
report['error'] = 'Сборка или тестирование прерваны оператором.'
|
|
code = 130
|
|
except (OSError, RuntimeError) as error:
|
|
report['status'] = 'FAIL'
|
|
report['error'] = str(error)
|
|
print('\n' + str(error), file=sys.stderr)
|
|
finally:
|
|
report['finished_at'] = utc_now()
|
|
(report_dir / 'result.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
|
archive = report_dir.with_suffix('.tar.gz')
|
|
with tarfile.open(str(archive), 'w:gz') as tar:
|
|
tar.add(str(report_dir), arcname=report_dir.name)
|
|
print('\nРезультат: {}. Архив отчёта: {}'.format(report['status'], archive), flush=True)
|
|
print('PASS означает сборку и локальные тесты. Испытания домена и допуск релиза остаются отдельными.')
|
|
if code == 0:
|
|
print('\nЗапуск из рабочего стола Astra, без sudo:')
|
|
print('{} --project {}'.format(shlex.quote(str(build / 'ald-transition-console')),
|
|
shlex.quote(str(ROOT / 'astra-lab-project'))))
|
|
return code
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|