publish.py 22 KB

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