publish.py 22 KB

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