publish.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. #!/usr/bin/env python
  2. # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
  3. import argparse
  4. import base64
  5. import contextlib
  6. import datetime
  7. import glob
  8. import io
  9. import json
  10. import mimetypes
  11. import os
  12. import pprint
  13. import re
  14. import shlex
  15. import shutil
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import time
  20. from contextlib import contextmanager, suppress
  21. from http.client import HTTPResponse, HTTPSConnection
  22. from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union
  23. from urllib.parse import urlencode, urlparse
  24. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  25. docs_dir = os.path.abspath('docs')
  26. publish_dir = os.path.abspath(os.path.join('..', 'kovidgoyal.github.io', 'kitty'))
  27. building_nightly = False
  28. with open('kitty/constants.py') as f:
  29. raw = f.read()
  30. nv = re.search(r'^version: Version\s+=\s+Version\((\d+), (\d+), (\d+)\)', raw, flags=re.MULTILINE)
  31. if nv is not None:
  32. version = f'{nv.group(1)}.{nv.group(2)}.{nv.group(3)}'
  33. ap = re.search(r"^appname: str\s+=\s+'([^']+)'", raw, flags=re.MULTILINE)
  34. if ap is not None:
  35. appname = ap.group(1)
  36. ALL_ACTIONS = 'local_build man html build tag sdist upload website'.split()
  37. NIGHTLY_ACTIONS = 'local_build man html build sdist upload_nightly'.split()
  38. def echo_cmd(cmd: Iterable[str]) -> None:
  39. isatty = sys.stdout.isatty()
  40. end = '\n'
  41. if isatty:
  42. end = f'\x1b[m{end}'
  43. print('\x1b[32m', end='')
  44. print(shlex.join(cmd), end=end, flush=True)
  45. def call(*cmd: str, cwd: Optional[str] = None, echo: bool = False) -> None:
  46. if len(cmd) == 1:
  47. q = shlex.split(cmd[0])
  48. else:
  49. q = list(cmd)
  50. if echo:
  51. echo_cmd(cmd)
  52. ret = subprocess.Popen(q, cwd=cwd).wait()
  53. if ret != 0:
  54. raise SystemExit(ret)
  55. def run_local_build(args: Any) -> None:
  56. call('make debug')
  57. def run_build(args: Any) -> None:
  58. import runpy
  59. m = runpy.run_path('./setup.py', run_name='__publish__')
  60. vcs_rev: str = m['get_vcs_rev']()
  61. def run_with_retry(cmd: str) -> None:
  62. try:
  63. call(cmd, echo=True)
  64. except (SystemExit, Exception):
  65. needs_retry = building_nightly and 'linux' not in cmd
  66. if not needs_retry:
  67. raise
  68. print('Build failed, retrying in a minute seconds...', file=sys.stderr)
  69. if 'macos' in cmd:
  70. call('python ../bypy macos shutdown')
  71. time.sleep(60)
  72. call(cmd, echo=True)
  73. for x in ('64', 'arm64'):
  74. prefix = f'python ../bypy linux --arch {x} '
  75. run_with_retry(prefix + f'program --non-interactive --extra-program-data "{vcs_rev}"')
  76. run_with_retry(f'python ../bypy macos program --sign-installers --notarize --non-interactive --extra-program-data "{vcs_rev}"')
  77. call('python ../bypy macos shutdown', echo=True)
  78. call('make debug')
  79. call('./setup.py build-static-binaries')
  80. def run_tag(args: Any) -> None:
  81. call('git push')
  82. call('git tag -s v{0} -m version-{0}'.format(version))
  83. call(f'git push origin v{version}')
  84. def run_man(args: Any) -> None:
  85. call('make FAIL_WARN=1 man', cwd=docs_dir)
  86. def run_html(args: Any) -> None:
  87. # Force a fresh build otherwise the search index is not correct
  88. with suppress(FileNotFoundError):
  89. shutil.rmtree(os.path.join(docs_dir, '_build', 'dirhtml'))
  90. call('make FAIL_WARN=1 "OPTS=-D analytics_id=G-XTJK3R7GF2" dirhtml', cwd=docs_dir)
  91. add_old_redirects('docs/_build/dirhtml')
  92. with suppress(FileNotFoundError):
  93. shutil.rmtree(os.path.join(docs_dir, '_build', 'html'))
  94. call('make FAIL_WARN=1 "OPTS=-D analytics_id=G-XTJK3R7GF2" html', cwd=docs_dir)
  95. def generate_redirect_html(link_name: str, bname: str) -> None:
  96. with open(link_name, 'w') as f:
  97. f.write(f'''
  98. <html>
  99. <head>
  100. <title>Redirecting...</title>
  101. <link rel="canonical" href="{bname}/" />
  102. <noscript>
  103. <meta http-equiv="refresh" content="0;url={bname}/" />
  104. </noscript>
  105. <script type="text/javascript">
  106. window.location.replace('./{bname}/' + window.location.hash);
  107. </script>
  108. </head>
  109. <body>
  110. <p>Redirecting, please wait...</p>
  111. </body>
  112. </html>
  113. ''')
  114. def add_old_redirects(loc: str) -> None:
  115. for dirpath, dirnames, filenames in os.walk(loc):
  116. if dirpath != loc:
  117. for fname in filenames:
  118. if fname == 'index.html':
  119. bname = os.path.basename(dirpath)
  120. base = os.path.dirname(dirpath)
  121. link_name = os.path.join(base, f'{bname}.html') if base else f'{bname}.html'
  122. generate_redirect_html(link_name, bname)
  123. old_unicode_input_path = os.path.join(loc, 'kittens', 'unicode-input')
  124. os.makedirs(old_unicode_input_path, exist_ok=True)
  125. generate_redirect_html(os.path.join(old_unicode_input_path, 'index.html'), '../unicode_input')
  126. generate_redirect_html(f'{old_unicode_input_path}.html', 'unicode_input')
  127. def run_docs(args: Any) -> None:
  128. subprocess.check_call(['make', 'docs'])
  129. def run_website(args: Any) -> None:
  130. if os.path.exists(publish_dir):
  131. shutil.rmtree(publish_dir)
  132. shutil.copytree(os.path.join(docs_dir, '_build', 'dirhtml'), publish_dir, symlinks=True)
  133. with open(os.path.join(publish_dir, 'current-version.txt'), 'w') as f:
  134. f.write(version)
  135. shutil.copy2(os.path.join(docs_dir, 'installer.sh'), publish_dir)
  136. os.chdir(os.path.dirname(publish_dir))
  137. subprocess.check_call(['optipng', '-o7'] + glob.glob('kitty/_images/social_previews/*.png'))
  138. subprocess.check_call(['git', 'add', 'kitty'])
  139. subprocess.check_call(['git', 'commit', '-m', 'kitty website updates'])
  140. subprocess.check_call(['git', 'push'])
  141. def sign_file(path: str) -> None:
  142. dest = f'{path}.sig'
  143. with suppress(FileNotFoundError):
  144. os.remove(dest)
  145. subprocess.check_call([
  146. os.environ['PENV'] + '/gpg-as-kovid', '--output', f'{path}.sig',
  147. '--detach-sig', path
  148. ])
  149. def run_sdist(args: Any) -> None:
  150. with tempfile.TemporaryDirectory() as tdir:
  151. base = os.path.join(tdir, f'kitty-{version}')
  152. os.mkdir(base)
  153. subprocess.check_call(f'git archive HEAD | tar -x -C {base}', shell=True)
  154. dest = os.path.join(base, 'docs', '_build')
  155. os.mkdir(dest)
  156. for x in 'html man'.split():
  157. shutil.copytree(os.path.join(docs_dir, '_build', x), os.path.join(dest, x))
  158. dest = os.path.abspath(os.path.join('build', f'kitty-{version}.tar'))
  159. subprocess.check_call(['tar', '-cf', dest, os.path.basename(base)], cwd=tdir)
  160. with suppress(FileNotFoundError):
  161. os.remove(f'{dest}.xz')
  162. subprocess.check_call(['xz', '-9', dest])
  163. sign_file(f'{dest}.xz')
  164. class ReadFileWithProgressReporting(io.FileIO): # {{{
  165. def __init__(self, path: str):
  166. super().__init__(path, 'rb')
  167. self.seek(0, os.SEEK_END)
  168. self._total = self.tell()
  169. self.seek(0)
  170. self.start_time = time.monotonic()
  171. print('Starting upload of:', os.path.basename(path), 'size:', self._total)
  172. def __len__(self) -> int:
  173. return self._total
  174. def read(self, size: Optional[int] = -1) -> bytes:
  175. data = io.FileIO.read(self, size)
  176. if data:
  177. self.report_progress(len(data))
  178. return data
  179. def report_progress(self, size: int) -> None:
  180. def write(*args: str) -> None:
  181. print(*args, end='')
  182. frac = int(self.tell() * 100 / self._total)
  183. mb_pos = self.tell() / float(1024**2)
  184. mb_tot = self._total / float(1024**2)
  185. kb_pos = self.tell() / 1024.0
  186. kb_rate = kb_pos / (time.monotonic() - self.start_time)
  187. bit_rate = kb_rate * 1024
  188. eta = int((self._total - self.tell()) / bit_rate) + 1
  189. eta_m, eta_s = divmod(eta, 60)
  190. if sys.stdout.isatty():
  191. write(
  192. f'\r\033[K\033[?7h {frac}% {mb_pos:.1f}/{mb_tot:.1f}MB {kb_rate:.1f} KB/sec {eta_m} minutes, {eta_s} seconds left\033[?7l')
  193. if self.tell() >= self._total:
  194. t = int(time.monotonic() - self.start_time) + 1
  195. print(f'\nUpload took {t//60} minutes and {t%60} seconds at {kb_rate:.1f} KB/sec')
  196. sys.stdout.flush()
  197. # }}}
  198. class GitHub: # {{{
  199. API = 'https://api.github.com'
  200. def __init__(
  201. self,
  202. files: Dict[str, str],
  203. reponame: str,
  204. version: str,
  205. username: str,
  206. password: str,
  207. replace: bool = False
  208. ):
  209. self.files, self.reponame, self.version, self.username, self.password, self.replace = (
  210. files, reponame, version, username, password, replace)
  211. self.current_tag_name = self.version if self.version == 'nightly' else f'v{self.version}'
  212. self.is_nightly = self.current_tag_name == 'nightly'
  213. self.auth = 'Basic ' + base64.standard_b64encode(f'{self.username}:{self.password}'.encode()).decode()
  214. self.url_base = f'{self.API}/repos/{self.username}/{self.reponame}/releases'
  215. def info(self, *args: Any) -> None:
  216. print(*args, flush=True)
  217. def error(self, *args: Any) -> None:
  218. print(*args, flush=True, file=sys.stderr)
  219. def make_request(
  220. self, url: str, data: Optional[Dict[str, Any]] = None, method:str = 'GET',
  221. upload_data: Optional[ReadFileWithProgressReporting] = None,
  222. params: Optional[Dict[str, str]] = None,
  223. ) -> HTTPSConnection:
  224. headers={
  225. 'Authorization': self.auth,
  226. 'Accept': 'application/vnd.github+json',
  227. 'User-Agent': 'kitty',
  228. 'X-GitHub-Api-Version': '2022-11-28',
  229. }
  230. if params:
  231. url += '?' + urlencode(params)
  232. rdata: Optional[Union[bytes, io.FileIO]] = None
  233. if data is not None:
  234. rdata = json.dumps(data).encode('utf-8')
  235. headers['Content-Type'] = 'application/json'
  236. headers['Content-Length'] = str(len(rdata))
  237. elif upload_data is not None:
  238. rdata = upload_data
  239. mime_type = mimetypes.guess_type(os.path.basename(str(upload_data.name)))[0] or 'application/octet-stream'
  240. headers['Content-Type'] = mime_type
  241. headers['Content-Length'] = str(upload_data._total)
  242. purl = urlparse(url)
  243. conn = HTTPSConnection(purl.netloc, timeout=60)
  244. conn.request(method, url, body=rdata, headers=headers)
  245. return conn
  246. def make_request_with_retries(
  247. self, url: str, data: Optional[Dict[str, str]] = None, method:str = 'GET',
  248. num_tries: int = 2, sleep_between_tries: float = 15,
  249. success_codes: Tuple[int, ...] = (200,),
  250. failure_msg: str = 'Request failed',
  251. return_data: bool = False,
  252. upload_path: str = '',
  253. params: Optional[Dict[str, str]] = None,
  254. failure_callback: Callable[[HTTPResponse], None] = lambda r: None,
  255. ) -> Any:
  256. for i in range(num_tries):
  257. is_last_try = i == num_tries - 1
  258. try:
  259. if upload_path:
  260. conn = self.make_request(url, method='POST', upload_data=ReadFileWithProgressReporting(upload_path), params=params)
  261. else:
  262. conn = self.make_request(url, data, method, params=params)
  263. with contextlib.closing(conn):
  264. r = conn.getresponse()
  265. if r.status in success_codes:
  266. return json.loads(r.read()) if return_data else None
  267. if is_last_try:
  268. self.fail(r, failure_msg)
  269. else:
  270. self.print_failed_response_details(r, failure_msg)
  271. failure_callback(r)
  272. except Exception as e:
  273. self.error(failure_msg, 'with error:', e)
  274. self.error(f'Retrying after {sleep_between_tries} seconds')
  275. if is_last_try:
  276. break
  277. time.sleep(sleep_between_tries)
  278. raise SystemExit('All retries failed, giving up')
  279. def patch(self, url: str, fail_msg: str, **data: str) -> None:
  280. self.make_request_with_retries(url, data, method='PATCH', failure_msg=fail_msg)
  281. def update_nightly_description(self, release_id: int) -> None:
  282. url = f'{self.url_base}/{release_id}'
  283. now = str(datetime.datetime.now(datetime.timezone.utc)).split('.')[0] + ' UTC'
  284. commit = subprocess.check_output(['git', 'rev-parse', '--verify', '--end-of-options', 'master^{commit}']).decode('utf-8').strip()
  285. self.patch(
  286. url, 'Failed to update nightly release description',
  287. body=f'Nightly release, generated on: {now} from commit: {commit}.'
  288. ' For how to install nightly builds, see: https://sw.kovidgoyal.net/kitty/binary/#customizing-the-installation'
  289. )
  290. def __call__(self) -> None:
  291. # See https://docs.github.com/en/rest/releases/assets#upload-a-release-asset
  292. release = self.create_release()
  293. upload_url = release['upload_url'].partition('{')[0]
  294. all_assest_for_release = self.existing_assets_for_release(release)
  295. assets_by_fname = {a['name']:a for a in all_assest_for_release}
  296. def delete_asset(asset: Dict[str, Any], allow_not_found: bool = True) -> None:
  297. success_codes = [204]
  298. if allow_not_found:
  299. success_codes.append(404)
  300. self.make_request_with_retries(
  301. asset['url'], method='DELETE', num_tries=5, sleep_between_tries=2, success_codes=tuple(success_codes),
  302. failure_msg='Failed to delete asset from GitHub')
  303. def upload_with_retries(path: str, desc: str, num_tries: int = 8, sleep_time: float = 60.0) -> None:
  304. fname = os.path.basename(path)
  305. if self.is_nightly:
  306. fname = fname.replace(version, 'nightly')
  307. if fname in assets_by_fname:
  308. self.info(f'Deleting {fname} from GitHub with id: {assets_by_fname[fname]["id"]}')
  309. delete_asset(assets_by_fname.pop(fname))
  310. params = {'name': fname, 'label': desc}
  311. self.make_request_with_retries(
  312. upload_url, upload_path=path, params=params, num_tries=num_tries, sleep_between_tries=sleep_time,
  313. failure_msg=f'Failed to upload file: {fname}', success_codes=(201,),
  314. )
  315. if self.is_nightly:
  316. for fname in tuple(assets_by_fname):
  317. self.info(f'Deleting {fname} from GitHub with id: {assets_by_fname[fname]["id"]}')
  318. delete_asset(assets_by_fname.pop(fname))
  319. for path, desc in self.files.items():
  320. self.info('')
  321. upload_with_retries(path, desc)
  322. if self.is_nightly:
  323. self.update_nightly_description(release['id'])
  324. def print_failed_response_details(self, r: HTTPResponse, msg: str) -> None:
  325. self.error(msg, f'\nStatus Code: {r.status} {r.reason}')
  326. try:
  327. jr = json.loads(r.read())
  328. except Exception:
  329. pass
  330. else:
  331. self.error('JSON from response:')
  332. pprint.pprint(jr, stream=sys.stderr)
  333. def fail(self, r: HTTPResponse, msg: str) -> None:
  334. self.print_failed_response_details(r, msg)
  335. raise SystemExit(1)
  336. def existing_assets_for_release(self, release: Dict[str, Any]) -> List[Dict[str, Any]]:
  337. if 'assets' in release:
  338. d: List[Dict[str, Any]] = release['assets']
  339. else:
  340. d = self.make_request_with_retries(
  341. release['assets_url'], params={'per_page': '64'}, failure_msg='Failed to get assets for release', return_data=True)
  342. return d
  343. def create_release(self) -> Dict[str, Any]:
  344. ' Create a release on GitHub or if it already exists, return the existing release '
  345. # Check for existing release
  346. url = f'{self.url_base}/tags/{self.current_tag_name}'
  347. with contextlib.closing(self.make_request(url)) as conn:
  348. r = conn.getresponse()
  349. if r.status == 200:
  350. return {str(k): v for k, v in json.loads(r.read()).items()}
  351. if self.is_nightly:
  352. self.fail(r, 'No existing nightly release found on GitHub')
  353. data = {
  354. 'tag_name': self.current_tag_name,
  355. 'target_commitish': 'master',
  356. 'name': f'version {self.version}',
  357. 'body': f'Release version {self.version}.'
  358. ' For changelog, see https://sw.kovidgoyal.net/kitty/changelog/#detailed-list-of-changes'
  359. ' GPG key used for signing tarballs is: https://calibre-ebook.com/signatures/kovid.gpg',
  360. 'draft': False,
  361. 'prerelease': False
  362. }
  363. with contextlib.closing(self.make_request(self.url_base, method='POST', data=data)) as conn:
  364. r = conn.getresponse()
  365. if r.status != 201:
  366. self.fail(r, f'Failed to create release for version: {self.version}')
  367. return {str(k): v for k, v in json.loads(r.read()).items()}
  368. # }}}
  369. def get_github_data() -> Dict[str, str]:
  370. with open(os.environ['PENV'] + '/github-token') as f:
  371. un, pw = f.read().strip().split(':')
  372. return {'username': un, 'password': pw}
  373. def files_for_upload() -> Dict[str, str]:
  374. files = {}
  375. signatures = {}
  376. for f, desc in {
  377. 'macos/dist/kitty-{}.dmg': 'macOS dmg',
  378. 'linux/64/dist/kitty-{}-x86_64.txz': 'Linux amd64 binary bundle',
  379. 'linux/arm64/dist/kitty-{}-arm64.txz': 'Linux arm64 binary bundle',
  380. }.items():
  381. path = os.path.join('bypy', 'b', f.format(version))
  382. if not os.path.exists(path):
  383. raise SystemExit(f'The installer {path} does not exist')
  384. files[path] = desc
  385. signatures[path] = f'GPG signature for {desc}'
  386. b = len(files)
  387. for path in glob.glob('build/static/kitten-*'):
  388. if path.endswith('.sig'):
  389. continue
  390. path = os.path.abspath(path)
  391. exe_name = os.path.basename(path)
  392. files[path] = f'Static {exe_name} executable'
  393. signatures[path] = f'GPG signature for static {exe_name} executable'
  394. if len(files) == b:
  395. raise SystemExit('No static binaries found')
  396. files[f'build/kitty-{version}.tar.xz'] = 'Source code'
  397. files[f'build/kitty-{version}.tar.xz.sig'] = 'Source code GPG signature'
  398. for path, desc in signatures.items():
  399. sign_file(path)
  400. files[f'{path}.sig'] = desc
  401. for f in files:
  402. if not os.path.exists(f):
  403. raise SystemExit(f'The release artifact {f} does not exist')
  404. return files
  405. def run_upload(args: Any) -> None:
  406. gd = get_github_data()
  407. files = files_for_upload()
  408. gh = GitHub(files, appname, version, gd['username'], gd['password'])
  409. gh()
  410. def run_upload_nightly(args: Any) -> None:
  411. subprocess.check_call(['git', 'tag', '-f', 'nightly'])
  412. subprocess.check_call(['git', 'push', 'origin', 'nightly', '-f'])
  413. gd = get_github_data()
  414. files = files_for_upload()
  415. gh = GitHub(files, appname, 'nightly', gd['username'], gd['password'])
  416. gh()
  417. def current_branch() -> str:
  418. return subprocess.check_output(['git', 'symbolic-ref', '--short', 'HEAD']).decode('utf-8').strip()
  419. def require_git_master(branch: str = 'master') -> None:
  420. if current_branch() != branch:
  421. raise SystemExit(f'You must be in the {branch} git branch')
  422. def safe_read(path: str) -> str:
  423. with suppress(FileNotFoundError):
  424. with open(path) as f:
  425. return f.read()
  426. return ''
  427. def remove_pycache_only_folders() -> None:
  428. folders_to_remove = []
  429. for dirpath, folders, files in os.walk('.'):
  430. if not files and folders == ['__pycache__']:
  431. folders_to_remove.append(dirpath)
  432. for x in folders_to_remove:
  433. shutil.rmtree(x)
  434. @contextmanager
  435. def change_to_git_master() -> Generator[None, None, None]:
  436. stash_ref_before = safe_read('.git/refs/stash')
  437. subprocess.check_call(['git', 'stash', '-u'])
  438. try:
  439. branch_before = current_branch()
  440. if branch_before != 'master':
  441. subprocess.check_call(['git', 'switch', 'master'])
  442. remove_pycache_only_folders()
  443. subprocess.check_call(['make', 'clean', 'debug'])
  444. try:
  445. yield
  446. finally:
  447. if branch_before != 'master':
  448. subprocess.check_call(['git', 'switch', branch_before])
  449. subprocess.check_call(['make', 'clean', 'debug'])
  450. finally:
  451. if stash_ref_before != safe_read('.git/refs/stash'):
  452. subprocess.check_call(['git', 'stash', 'pop'])
  453. def require_penv() -> None:
  454. if 'PENV' not in os.environ:
  455. raise SystemExit('The PENV env var is not present, required for uploading releases')
  456. def exec_actions(actions: Iterable[str], args: Any) -> None:
  457. for action in actions:
  458. print('Running', action)
  459. cwd = os.getcwd()
  460. globals()[f'run_{action}'](args)
  461. os.chdir(cwd)
  462. def main() -> None:
  463. global building_nightly
  464. parser = argparse.ArgumentParser(description='Publish kitty')
  465. parser.add_argument(
  466. '--only',
  467. default=False,
  468. action='store_true',
  469. help='Only run the specified action, by default the specified action and all sub-sequent actions are run')
  470. parser.add_argument(
  471. '--nightly',
  472. default=False,
  473. action='store_true',
  474. help='Upload a nightly release, ignores all other arguments')
  475. parser.add_argument(
  476. 'action',
  477. default='all',
  478. nargs='?',
  479. choices=list(ALL_ACTIONS) + ['all', 'upload_nightly'],
  480. help='The action to start with')
  481. args = parser.parse_args()
  482. require_penv()
  483. if args.nightly:
  484. with change_to_git_master():
  485. building_nightly = True
  486. exec_actions(NIGHTLY_ACTIONS, args)
  487. subprocess.run(['make', 'clean', 'debug'])
  488. return
  489. require_git_master()
  490. if args.action == 'all':
  491. actions = list(ALL_ACTIONS)
  492. elif args.action == 'upload_nightly':
  493. actions = ['upload_nightly']
  494. else:
  495. idx = ALL_ACTIONS.index(args.action)
  496. actions = ALL_ACTIONS[idx:]
  497. if args.only:
  498. del actions[1:]
  499. else:
  500. try:
  501. ans = input(f'Publish version \033[91m{version}\033[m (y/n): ')
  502. except KeyboardInterrupt:
  503. ans = 'n'
  504. if ans.lower() != 'y':
  505. return
  506. if actions == ['website']:
  507. actions.insert(0, 'html')
  508. exec_actions(actions, args)
  509. if __name__ == '__main__':
  510. main()