brainframe-cli 0.1.6.dev1__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of brainframe-cli might be problematic. Click here for more details.

Files changed (34) hide show
  1. brainframe/cli/__init__.py +1 -0
  2. brainframe/cli/brainframe_compose.py +185 -0
  3. brainframe/cli/commands/__init__.py +3 -1
  4. brainframe/cli/commands/backup.py +13 -17
  5. brainframe/cli/commands/compose.py +5 -20
  6. brainframe/cli/commands/info.py +10 -7
  7. brainframe/cli/commands/install.py +33 -89
  8. brainframe/cli/commands/self_update.py +123 -0
  9. brainframe/cli/commands/uninstall.py +76 -0
  10. brainframe/cli/commands/update.py +53 -20
  11. brainframe/cli/commands/utils.py +19 -0
  12. brainframe/cli/config.py +95 -0
  13. brainframe/cli/defaults.yaml +4 -0
  14. brainframe/cli/dependencies.py +17 -30
  15. brainframe/cli/frozen_utils.py +47 -0
  16. brainframe/cli/main.py +21 -16
  17. brainframe/cli/os_utils.py +68 -17
  18. brainframe/cli/print_utils.py +5 -4
  19. brainframe/cli/translations/general.en.yml +19 -2
  20. brainframe/cli/translations/install.en.yml +1 -16
  21. brainframe/cli/translations/portal.en.yml +1 -1
  22. brainframe/cli/translations/self-update.en.yml +17 -0
  23. brainframe/cli/translations/uninstall.en.yml +23 -0
  24. brainframe/cli/translations/update.en.yml +18 -6
  25. brainframe_cli-0.3.0.dist-info/COPYING +26 -0
  26. brainframe_cli-0.3.0.dist-info/METADATA +121 -0
  27. brainframe_cli-0.3.0.dist-info/RECORD +31 -0
  28. {brainframe_cli-0.1.6.dev1.dist-info → brainframe_cli-0.3.0.dist-info}/WHEEL +1 -1
  29. brainframe/cli/docker_compose.py +0 -100
  30. brainframe/cli/env_vars.py +0 -55
  31. brainframe/cli/translations/compose.en.yml +0 -8
  32. brainframe_cli-0.1.6.dev1.dist-info/METADATA +0 -68
  33. brainframe_cli-0.1.6.dev1.dist-info/RECORD +0 -24
  34. {brainframe_cli-0.1.6.dev1.dist-info → brainframe_cli-0.3.0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -0,0 +1,185 @@
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ from pathlib import Path
5
+ from typing import List
6
+ from typing import Optional
7
+ from typing import Tuple
8
+
9
+ import i18n
10
+ import requests
11
+ import yaml
12
+
13
+ from . import config
14
+ from . import frozen_utils
15
+ from . import os_utils
16
+ from . import print_utils
17
+
18
+ # The URL to the docker-compose.yml
19
+ BRAINFRAME_DOCKER_COMPOSE_URL = "https://{subdomain}aotu.ai/releases/brainframe/{version}/docker-compose.yml"
20
+ # The URL to the latest tag, which is just a file containing the latest version
21
+ # as a string
22
+ BRAINFRAME_LATEST_TAG_URL = (
23
+ "https://{subdomain}aotu.ai/releases/brainframe/latest"
24
+ )
25
+
26
+
27
+ def assert_installed(install_path: Path) -> None:
28
+ compose_path = install_path / "docker-compose.yml"
29
+
30
+ if not compose_path.is_file():
31
+ print_utils.fail_translate(
32
+ "general.brainframe-must-be-installed",
33
+ install_env_var=config.install_path.name,
34
+ )
35
+
36
+
37
+ def get_docker_compose_command():
38
+ try:
39
+ # First, try to use 'docker compose'
40
+ compose_version = subprocess.check_output(
41
+ ["docker", "compose", "version", "--short"],
42
+ stderr=subprocess.DEVNULL,
43
+ )
44
+ return ["docker", "compose"], compose_version
45
+ except subprocess.CalledProcessError as e2:
46
+ try:
47
+ compose_version = subprocess.check_output(
48
+ ["docker-compose", "version", "--short"],
49
+ stderr=subprocess.DEVNULL,
50
+ )
51
+ return ["docker-compose"], compose_version
52
+ except subprocess.CalledProcessError as e1:
53
+ message = f"Docker Compose V1: {e}; V2: {e}"
54
+ raise DockerComposeNotFoundError(message)
55
+
56
+
57
+ def run(install_path: Path, commands: List[str]) -> None:
58
+ _assert_has_docker_permissions()
59
+
60
+ compose_path = install_path / "docker-compose.yml"
61
+
62
+ full_command, _ = get_docker_compose_command()
63
+
64
+ full_command += [
65
+ "--file",
66
+ str(compose_path),
67
+ ]
68
+
69
+ # Provide the override file if it exists
70
+ compose_override_path = install_path / "docker-compose.override.yml"
71
+ if compose_override_path.is_file():
72
+ full_command += ["--file", str(compose_override_path)]
73
+
74
+ # Provide the .env file if it exists
75
+ env_path = install_path / ".env"
76
+ if env_path.is_file():
77
+ full_command += ["--env-file", str(env_path)]
78
+
79
+ additional_help = None
80
+ if "down" in commands:
81
+ if "--except-volumes" in commands:
82
+ commands.remove("--except-volumes")
83
+ else:
84
+ if "--volumes" not in commands:
85
+ commands += ["--volumes"]
86
+ if "--help" in commands:
87
+ additional_help = ' --except-volumes Do not add --volumes to "brainframe compose down"'
88
+
89
+ os_utils.run(full_command + commands)
90
+
91
+ if additional_help is not None:
92
+ print_utils.print_color(
93
+ additional_help, color=print_utils.Color.MAGENTA, file=sys.stderr
94
+ )
95
+
96
+
97
+ def download(target: Path, version: str = "latest") -> None:
98
+ _assert_has_write_permissions(target.parent)
99
+
100
+ if version == "latest":
101
+ version = get_latest_version()
102
+
103
+ credentials = config.staging_credentials()
104
+
105
+ url = BRAINFRAME_DOCKER_COMPOSE_URL.format(
106
+ subdomain="staging." if config.is_staging.value else "",
107
+ version=version,
108
+ )
109
+ response = requests.get(url, auth=credentials, stream=True)
110
+ if not response.ok:
111
+ print_utils.fail_translate(
112
+ "general.error-downloading-docker-compose",
113
+ status_code=response.status_code,
114
+ error_message=response.text,
115
+ )
116
+
117
+ target.write_text(response.text)
118
+
119
+ if os_utils.is_root():
120
+ # Fix the permissions of the docker-compose.yml so that the BrainFrame
121
+ # group can edit it
122
+ os_utils.give_brainframe_group_rw_access([target])
123
+
124
+
125
+ def get_latest_version() -> str:
126
+ """
127
+ :return: The latest available version in the format "vX.Y.Z"
128
+ """
129
+ # Add the flags to authenticate with staging if the user wants to download
130
+ # from there
131
+ subdomain = "staging." if config.is_staging.value else ""
132
+ credentials = config.staging_credentials()
133
+
134
+ # Check what the latest version is
135
+ url = BRAINFRAME_LATEST_TAG_URL.format(subdomain=subdomain)
136
+ response = requests.get(url, auth=credentials)
137
+ return response.text
138
+
139
+
140
+ def check_existing_version(install_path: Path) -> str:
141
+ compose_path = install_path / "docker-compose.yml"
142
+ compose = yaml.load(compose_path.read_text(), Loader=yaml.SafeLoader)
143
+ version = compose["services"]["core"]["image"].split(":")[-1]
144
+ version = "v" + version
145
+ return version
146
+
147
+
148
+ def _assert_has_docker_permissions() -> None:
149
+ """Fails if the user does not have permissions to interact with Docker"""
150
+ if not (os_utils.is_root() or os_utils.currently_in_group("docker")):
151
+ error_message = (
152
+ i18n.t("general.docker-bad-permissions")
153
+ + "\n"
154
+ + _group_recommendation_message("docker")
155
+ )
156
+
157
+ print_utils.fail(error_message)
158
+
159
+
160
+ def _assert_has_write_permissions(path: Path) -> None:
161
+ """Fails if the user does not have write access to the given path."""
162
+ if os.access(path, os.W_OK):
163
+ return
164
+
165
+ error_message = i18n.t("general.file-bad-write-permissions", path=path)
166
+ error_message += "\n"
167
+
168
+ if path.stat().st_gid == os_utils.BRAINFRAME_GROUP_ID:
169
+ error_message += " " + _group_recommendation_message("brainframe")
170
+ else:
171
+ error_message += " " + i18n.t(
172
+ "general.unexpected-group-for-file", path=path, group="brainframe"
173
+ )
174
+
175
+ print_utils.fail(error_message)
176
+
177
+
178
+ def _group_recommendation_message(group: str) -> str:
179
+ if os_utils.added_to_group("brainframe"):
180
+ # The user is in the group, they just need to restart
181
+ return i18n.t("general.restart-for-group-access", group=group)
182
+ else:
183
+ # The user is not in the group, so they need to either add
184
+ # themselves or use sudo
185
+ return i18n.t("general.retry-as-root-or-group", group=group)
@@ -1,6 +1,8 @@
1
1
  from .backup import backup
2
2
  from .compose import compose
3
+ from .info import info
3
4
  from .install import install
5
+ from .self_update import self_update
6
+ from .uninstall import uninstall
4
7
  from .update import update
5
- from .info import info
6
8
  from .utils import by_name
@@ -4,32 +4,28 @@ from datetime import datetime
4
4
  from pathlib import Path
5
5
 
6
6
  import i18n
7
+ from brainframe.cli import brainframe_compose
8
+ from brainframe.cli import config
9
+ from brainframe.cli import dependencies
10
+ from brainframe.cli import os_utils
11
+ from brainframe.cli import print_utils
7
12
 
8
- from brainframe.cli import (
9
- print_utils,
10
- docker_compose,
11
- os_utils,
12
- dependencies,
13
- env_vars,
14
- )
15
- from .utils import subcommand_parse_args, command
13
+ from .utils import command
14
+ from .utils import requires_root
15
+ from .utils import subcommand_parse_args
16
16
 
17
17
  BACKUP_DIR_FORMAT = "%Y-%m-%d_%H-%M-%S"
18
18
 
19
19
 
20
20
  @command("backup")
21
+ @requires_root # Some BrainFrame services write files as root
21
22
  def backup():
22
- install_path = env_vars.install_path.get()
23
- data_path = env_vars.data_path.get()
23
+ install_path = config.install_path.value
24
+ data_path = config.data_path.value
24
25
 
25
26
  args = _parse_args(data_path)
26
27
 
27
- # This command has to be run as root for now because some BrainFrame
28
- # services write files as the root user.
29
- if not os_utils.is_root():
30
- print_utils.fail_translate("general.user-not-root")
31
-
32
- docker_compose.assert_installed(install_path)
28
+ brainframe_compose.assert_installed(install_path)
33
29
 
34
30
  dependencies.rsync.ensure(args.noninteractive, args.install_rsync)
35
31
 
@@ -40,7 +36,7 @@ def backup():
40
36
  # doesn't want that, stop the backup
41
37
  sys.exit(1)
42
38
 
43
- docker_compose.run(install_path, ["stop"])
39
+ brainframe_compose.run(install_path, ["stop"])
44
40
 
45
41
  if args.destination is None:
46
42
  now_str = datetime.now().strftime(BACKUP_DIR_FORMAT)
@@ -1,28 +1,13 @@
1
1
  import sys
2
2
 
3
- import i18n
3
+ from brainframe.cli import brainframe_compose
4
+ from brainframe.cli import config
4
5
 
5
- from brainframe.cli import docker_compose, env_vars, os_utils, print_utils
6
6
  from .utils import command
7
7
 
8
8
 
9
9
  @command("compose")
10
10
  def compose():
11
- # Check first if the user has permission to interact with Docker
12
- if not os_utils.is_root():
13
- if not os_utils.currently_in_group("docker"):
14
- error_message = i18n.t("compose.docker-bad-permissions") + "\n"
15
-
16
- if os_utils.added_to_group("docker"):
17
- # The user is in the group, they just need to restart
18
- error_message += i18n.t("compose.restart-for-group-access")
19
- else:
20
- # The user is not in the group, so they need to either add
21
- # themselves or use sudo
22
- error_message += i18n.t("compose.retry-with-sudo-or-group")
23
-
24
- print_utils.fail(error_message)
25
-
26
- install_path = env_vars.install_path.get()
27
- docker_compose.assert_installed(install_path)
28
- docker_compose.run(install_path, sys.argv[2:])
11
+ install_path = config.install_path.value
12
+ brainframe_compose.assert_installed(install_path)
13
+ brainframe_compose.run(install_path, sys.argv[2:])
@@ -1,24 +1,27 @@
1
1
  from argparse import ArgumentParser
2
2
 
3
3
  import i18n
4
+ from brainframe.cli import brainframe_compose
5
+ from brainframe.cli import config
6
+ from brainframe.cli import print_utils
4
7
 
5
- from brainframe.cli import env_vars, print_utils, docker_compose
6
- from .utils import subcommand_parse_args, command
8
+ from .utils import command
9
+ from .utils import subcommand_parse_args
7
10
 
8
11
 
9
12
  @command("info")
10
13
  def info():
11
14
  args = _parse_args()
12
15
 
13
- docker_compose.assert_installed(env_vars.install_path.get())
16
+ brainframe_compose.assert_installed(config.install_path.value)
14
17
 
15
- server_version = docker_compose.check_existing_version(
16
- env_vars.install_path.get()
18
+ server_version = brainframe_compose.check_existing_version(
19
+ config.install_path.value
17
20
  )
18
21
 
19
22
  fields = {
20
- "install_path": env_vars.install_path.get(),
21
- "data_path": env_vars.data_path.get(),
23
+ "install_path": config.install_path.value,
24
+ "data_path": config.data_path.value,
22
25
  "server_version": server_version,
23
26
  }
24
27
 
@@ -1,27 +1,25 @@
1
+ import shutil
1
2
  from argparse import ArgumentParser
2
3
  from pathlib import Path
3
- import json
4
- from urllib.request import urlopen
5
4
 
6
5
  import i18n
6
+ from brainframe.cli import brainframe_compose
7
+ from brainframe.cli import config
8
+ from brainframe.cli import dependencies
9
+ from brainframe.cli import frozen_utils
10
+ from brainframe.cli import os_utils
11
+ from brainframe.cli import print_utils
7
12
 
8
- from brainframe.cli import (
9
- print_utils,
10
- docker_compose,
11
- env_vars,
12
- os_utils,
13
- dependencies,
14
- )
15
- from .utils import subcommand_parse_args, command
13
+ from .utils import command
14
+ from .utils import requires_root
15
+ from .utils import subcommand_parse_args
16
16
 
17
17
 
18
18
  @command("install")
19
+ @requires_root
19
20
  def install():
20
21
  args = _parse_args()
21
22
 
22
- if not os_utils.is_root():
23
- print_utils.fail_translate("general.user-not-root")
24
-
25
23
  # Print some introductory text
26
24
  if not args.noninteractive:
27
25
  print_utils.art()
@@ -32,13 +30,15 @@ def install():
32
30
  print()
33
31
 
34
32
  # Check all dependencies
35
- dependencies.curl.ensure(args.noninteractive, args.install_curl)
36
33
  dependencies.docker.ensure(args.noninteractive, args.install_docker)
37
- dependencies.docker_compose.ensure(
38
- args.noninteractive, args.install_docker_compose
39
- )
34
+ # We only require the Docker Compose command in frozen distributions
35
+ if frozen_utils.is_frozen() and shutil.which("docker-compose") is None:
36
+ print_utils.fail_translate(
37
+ "install.install-dependency-manually",
38
+ dependency="docker-compose",
39
+ )
40
40
 
41
- _, _, download_version = docker_compose.check_download_version()
41
+ download_version = brainframe_compose.get_latest_version()
42
42
  print_utils.translate("install.install-version", version=download_version)
43
43
 
44
44
  if not os_utils.added_to_group("docker"):
@@ -57,8 +57,8 @@ def install():
57
57
  # Ask the user if they want to specify special paths for installation
58
58
  print_utils.translate(
59
59
  "install.default-paths",
60
- default_install_path=env_vars.install_path.default,
61
- default_data_path=env_vars.data_path.default,
60
+ default_install_path=config.install_path.default,
61
+ default_data_path=config.data_path.default,
62
62
  )
63
63
  use_default_paths = print_utils.ask_yes_no(
64
64
  "install.ask-use-default-paths",
@@ -68,11 +68,11 @@ def install():
68
68
  if args.noninteractive:
69
69
  install_path = args.install_path
70
70
  elif use_default_paths:
71
- install_path = env_vars.install_path.default
71
+ install_path = config.install_path.default
72
72
  else:
73
73
  install_path = print_utils.ask_path(
74
74
  "install.ask-brainframe-install-path",
75
- env_vars.install_path.default,
75
+ config.install_path.default,
76
76
  )
77
77
  install_path.mkdir(exist_ok=True, parents=True)
78
78
 
@@ -80,10 +80,10 @@ def install():
80
80
  if args.noninteractive:
81
81
  data_path = args.data_path
82
82
  elif use_default_paths:
83
- data_path = env_vars.data_path.default
83
+ data_path = config.data_path.default
84
84
  else:
85
85
  data_path = print_utils.ask_path(
86
- "install.ask-data-path", env_vars.data_path.default
86
+ "install.ask-data-path", config.data_path.default
87
87
  )
88
88
  data_path.mkdir(exist_ok=True, parents=True)
89
89
 
@@ -102,25 +102,18 @@ def install():
102
102
  if add_to_group:
103
103
  os_utils.add_to_group("brainframe")
104
104
 
105
- docker_compose.download(
105
+ brainframe_compose.download(
106
106
  install_path / "docker-compose.yml", version=args.version
107
107
  )
108
- location = check_location()
109
- try:
110
- docker_config = get_docker_config()
111
- except Exception:
112
- print_utils.warning_translate("install.fail-to-load-docker-config")
113
- else:
114
- update_docker_mirror(location=location, docker_config=docker_config)
115
108
 
116
109
  print_utils.translate("install.downloading-images")
117
- docker_compose.run(install_path, ["pull"])
110
+ brainframe_compose.run(install_path, ["pull"])
118
111
 
119
112
  print()
120
113
  print_utils.translate("install.complete", print_utils.Color.GREEN)
121
114
 
122
115
  if not args.noninteractive and print_utils.ask_yes_no("install.ask-start"):
123
- docker_compose.run(install_path, ["up", "-d"])
116
+ brainframe_compose.run(install_path, ["up", "-d"])
124
117
  print()
125
118
  print_utils.translate("install.running", print_utils.Color.GREEN)
126
119
  else:
@@ -129,15 +122,15 @@ def install():
129
122
  # Recommend to the user to add their custom paths to environment variables
130
123
  # so that future invocations of the program will know where to look.
131
124
  if (
132
- install_path != env_vars.install_path.default
133
- or data_path != env_vars.data_path.default
125
+ install_path != config.install_path.default
126
+ or data_path != config.data_path.default
134
127
  ):
135
128
  print()
136
129
  print_utils.translate("install.set-custom-directory-env-vars")
137
130
  print(
138
131
  f"\n"
139
- f'export {env_vars.install_path.name}="{install_path}"\n'
140
- f'export {env_vars.data_path.name}="{data_path}"\n'
132
+ f'export {config.install_path.env_var_name}="{install_path}"\n'
133
+ f'export {config.data_path.env_var_name}="{data_path}"\n'
141
134
  )
142
135
 
143
136
 
@@ -155,13 +148,13 @@ def _parse_args():
155
148
  parser.add_argument(
156
149
  "--install-path",
157
150
  type=Path,
158
- default=env_vars.install_path.default,
151
+ default=config.install_path.default,
159
152
  help=i18n.t("install.install-path-help"),
160
153
  )
161
154
  parser.add_argument(
162
155
  "--data-path",
163
156
  type=Path,
164
- default=env_vars.data_path.default,
157
+ default=config.data_path.default,
165
158
  help=i18n.t("install.data-path-help"),
166
159
  )
167
160
  parser.add_argument(
@@ -169,16 +162,6 @@ def _parse_args():
169
162
  action="store_true",
170
163
  help=i18n.t("install.install-docker-help"),
171
164
  )
172
- parser.add_argument(
173
- "--install-docker-compose",
174
- action="store_true",
175
- help=i18n.t("install.install-docker-compose-help"),
176
- )
177
- parser.add_argument(
178
- "--install-curl",
179
- action="store_true",
180
- help=i18n.t("install.install-curl-help"),
181
- )
182
165
  parser.add_argument(
183
166
  "--add-to-group",
184
167
  action="store_true",
@@ -197,42 +180,3 @@ def _parse_args():
197
180
  )
198
181
 
199
182
  return subcommand_parse_args(parser)
200
-
201
-
202
- def check_location() -> str:
203
- url = 'http://ipinfo.io/json'
204
- try:
205
- response = urlopen(url, timeout=5)
206
- except Exception:
207
- return "US"
208
- data = json.load(response)
209
- return data["country"]
210
-
211
-
212
- def get_docker_config() -> dict:
213
- with open("/etc/docker/daemon.json") as docker_config_file:
214
- docker_config = json.load(docker_config_file)
215
- return docker_config
216
-
217
-
218
- def update_docker_mirror(docker_config: dict, location: str):
219
- docker_mirror_host = {"CN": "USTC", "US": "Docker Hub"}
220
- if location == "CN" and \
221
- ("registry-mirrors" not in docker_config.keys() or
222
- docker_config["registry-mirrors"] !=
223
- ["https://docker.mirrors.ustc.edu.cn/"]):
224
- docker_config["registry-mirrors"] = \
225
- ["https://docker.mirrors.ustc.edu.cn/"]
226
- elif location != "CN" and "registry-mirrors" in docker_config.keys():
227
- del docker_config["registry-mirrors"]
228
- else:
229
- return
230
- if print_utils.ask_yes_no(
231
- "install.change-docker-mirror",
232
- location=location,
233
- mirror_host=docker_mirror_host[location]
234
- ):
235
- with open("/etc/docker/daemon.json", "w") as docker_config_file:
236
- json.dump(docker_config, docker_config_file, indent=4,
237
- sort_keys=True)
238
- os_utils.restart_docker()
@@ -0,0 +1,123 @@
1
+ import os
2
+ import shutil
3
+ import stat
4
+ import sys
5
+ from argparse import ArgumentParser
6
+ from pathlib import Path
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import Optional
9
+ from typing import Tuple
10
+ from typing import Union
11
+
12
+ import i18n
13
+ import requests
14
+ from brainframe.cli import __version__
15
+ from brainframe.cli import config
16
+ from brainframe.cli import frozen_utils
17
+ from brainframe.cli import print_utils
18
+ from packaging import version
19
+
20
+ from .utils import command
21
+
22
+ _RELEASES_URL_PREFIX = "https://{subdomain}aotu.ai"
23
+ _BINARY_URL = "{prefix}/releases/brainframe-cli/brainframe"
24
+ _LATEST_TAG_URL = "{prefix}/releases/brainframe-cli/latest"
25
+
26
+
27
+ @command("self-update")
28
+ def self_update():
29
+ _parse_args()
30
+
31
+ if not frozen_utils.is_frozen():
32
+ print_utils.fail_translate("self-update.not-frozen")
33
+
34
+ executable_path = Path(sys.executable)
35
+
36
+ # Check if the user has permissions to overwrite the executable in its
37
+ # current location
38
+ if not os.access(executable_path, os.W_OK):
39
+ error_message = i18n.t(
40
+ "general.file-bad-write-permissions", path=executable_path
41
+ )
42
+ error_message += "\n"
43
+ error_message += i18n.t("general.retry-as-root")
44
+ print_utils.fail(error_message)
45
+
46
+ credentials = config.staging_credentials()
47
+
48
+ prefix = _RELEASES_URL_PREFIX.format(
49
+ subdomain="staging." if config.is_staging.value else ""
50
+ )
51
+ binary_url = _BINARY_URL.format(prefix=prefix)
52
+
53
+ current_version = version.parse(__version__)
54
+ latest_version = _latest_version(prefix, credentials)
55
+
56
+ if current_version >= latest_version:
57
+ print_utils.fail_translate(
58
+ "self-update.already-up-to-date",
59
+ current_version=current_version,
60
+ latest_version=latest_version,
61
+ )
62
+
63
+ # Get the updated executable
64
+ print_utils.translate("self-update.downloading")
65
+ response = requests.get(binary_url, auth=credentials, stream=True)
66
+ if not response.ok:
67
+ print_utils.fail_translate(
68
+ "self-update.error-downloading",
69
+ status_code=response.status_code,
70
+ error_message=response.text,
71
+ )
72
+
73
+ with NamedTemporaryFile("wb") as new_executable:
74
+ for block in response.iter_content(_BLOCK_SIZE):
75
+ new_executable.write(block)
76
+ new_executable.flush()
77
+
78
+ # Set the result as executable
79
+ current_stat = executable_path.stat()
80
+ executable_path.chmod(
81
+ current_stat.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
82
+ )
83
+
84
+ # Overwrite the existing executable with the new one
85
+ # Really excited for copy3, coming this summer
86
+ shutil.copy2(new_executable.name, executable_path)
87
+
88
+ print()
89
+ print_utils.translate(
90
+ "self-update.complete", color=print_utils.Color.GREEN
91
+ )
92
+
93
+
94
+ def _latest_version(
95
+ url_prefix: str,
96
+ credentials: Optional[Tuple[str, str]],
97
+ ) -> Union[version.LegacyVersion, version.Version]:
98
+ latest_tag_url = _LATEST_TAG_URL.format(prefix=url_prefix)
99
+ response = requests.get(latest_tag_url, auth=credentials)
100
+
101
+ if not response.ok:
102
+ print_utils.fail_translate(
103
+ "self-update.error-getting-latest-version",
104
+ status_code=response.status_code,
105
+ error_message=response.text,
106
+ )
107
+
108
+ return version.parse(response.text)
109
+
110
+
111
+ def _parse_args():
112
+ parser = ArgumentParser(
113
+ description=i18n.t("self-update.description"),
114
+ usage=i18n.t("self-update.usage"),
115
+ )
116
+
117
+ return parser.parse_args(sys.argv[2:])
118
+
119
+
120
+ _BLOCK_SIZE = 1024000
121
+ """The block size to read files at. Chosen from this answer:
122
+ https://stackoverflow.com/a/3673731
123
+ """