snapctl 0.31.1__py3-none-any.whl → 0.32.1__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 snapctl might be problematic. Click here for more details.

snapctl/commands/game.py CHANGED
@@ -4,10 +4,13 @@
4
4
  import requests
5
5
  from requests.exceptions import RequestException
6
6
 
7
+ import typer
7
8
  from rich.progress import Progress, SpinnerColumn, TextColumn
8
- from snapctl.config.constants import SERVER_CALL_TIMEOUT
9
- from snapctl.types.definitions import ResponseType
9
+ from snapctl.config.constants import SERVER_CALL_TIMEOUT, SNAPCTL_INPUT_ERROR, \
10
+ SNAPCTL_SUCCESS, SNAPCTL_GAME_CREATE_ERROR, SNAPCTL_GAME_ENUMERATE_ERROR, \
11
+ HTTP_ERROR_DUPLICATE_GAME_NAME, SNAPCTL_GAME_CREATE_DUPLICATE_NAME_ERROR
10
12
  from snapctl.utils.echo import error, success
13
+ from snapctl.utils.helper import snapctl_error, snapctl_success
11
14
 
12
15
 
13
16
  class Game:
@@ -23,85 +26,88 @@ class Game:
23
26
  self.base_url: str = base_url
24
27
  self.api_key: str = api_key
25
28
  self.name: str | None = name
29
+ # Validate input
30
+ self.validate_input()
26
31
 
27
- def validate_input(self) -> ResponseType:
32
+ def validate_input(self) -> None:
28
33
  """
29
34
  Validator
30
35
  """
31
- response: ResponseType = {
32
- 'error': True,
33
- 'msg': '',
34
- 'data': []
35
- }
36
36
  # Check API Key and Base URL
37
37
  if not self.api_key or self.base_url == '':
38
- response['msg'] = "Missing API Key."
39
- return response
38
+ snapctl_error("Missing API Key.", SNAPCTL_INPUT_ERROR)
40
39
  # Check subcommand
41
40
  if not self.subcommand in Game.SUBCOMMANDS:
42
- response['msg'] = \
43
- f"Invalid command. Valid commands are {', '.join(Game.SUBCOMMANDS)}."
44
- return response
41
+ snapctl_error(
42
+ f"Invalid command. Valid commands are {', '.join(Game.SUBCOMMANDS)}.",
43
+ SNAPCTL_INPUT_ERROR)
45
44
  # Check sdk-download commands
46
45
  if self.subcommand == 'create':
47
46
  if self.name is None or self.name == '':
48
- response['msg'] = "Missing game name."
49
- return response
50
- # Send success
51
- response['error'] = False
52
- return response
47
+ snapctl_error("Missing game name.", SNAPCTL_INPUT_ERROR)
53
48
 
54
49
  def create(self) -> bool:
55
50
  """
56
51
  Create a game
57
52
  """
58
- with Progress(
53
+ progress = Progress(
59
54
  SpinnerColumn(),
60
55
  TextColumn("[progress.description]{task.description}"),
61
56
  transient=True,
62
- ) as progress:
63
- progress.add_task(
64
- description='Creating a new game on Snapser...', total=None)
65
- try:
66
- url = f"{self.base_url}/v1/snapser-api/games"
67
- payload = {
68
- 'name': self.name
69
- }
70
- res = requests.post(
71
- url, headers={'api-key': self.api_key},
72
- json=payload, timeout=SERVER_CALL_TIMEOUT
73
- )
74
- if res.ok:
75
- success(f"Game {self.name} has been created successfully.")
76
- return True
77
- error('Unable to create a new game. Reason: ' + res.text)
78
- except RequestException as e:
79
- error(f"Exception: Unable to download the SDK {e}")
80
- return False
57
+ )
58
+ progress.start()
59
+ progress.add_task(
60
+ description='Creating a new game on Snapser...', total=None)
61
+ try:
62
+ url = f"{self.base_url}/v1/snapser-api/games"
63
+ payload = {
64
+ 'name': self.name
65
+ }
66
+ res = requests.post(
67
+ url, headers={'api-key': self.api_key},
68
+ json=payload, timeout=SERVER_CALL_TIMEOUT
69
+ )
70
+ if res.ok:
71
+ snapctl_success(
72
+ f"Game {self.name} create successful", progress)
73
+ response_json = res.json()
74
+ if "api_error_code" in response_json and "message" in response_json:
75
+ if response_json['api_error_code'] == HTTP_ERROR_DUPLICATE_GAME_NAME:
76
+ snapctl_error(f"Game {self.name} already exists.",
77
+ SNAPCTL_GAME_CREATE_DUPLICATE_NAME_ERROR, progress)
78
+ snapctl_error(
79
+ f'Server error: {response_json}', SNAPCTL_GAME_CREATE_ERROR, progress)
80
+ except RequestException as e:
81
+ snapctl_error(f"Exception: Unable to download the SDK {e}",
82
+ SNAPCTL_GAME_CREATE_ERROR, progress)
83
+ snapctl_error('Failed to create game.',
84
+ SNAPCTL_GAME_CREATE_ERROR, progress)
81
85
 
82
86
  def enumerate(self) -> bool:
83
87
  """
84
88
  Enumerate all games
85
89
  """
86
- with Progress(
90
+ progress = Progress(
87
91
  SpinnerColumn(),
88
92
  TextColumn("[progress.description]{task.description}"),
89
93
  transient=True,
90
- ) as progress:
91
- progress.add_task(
92
- description='Enumerating all your games...', total=None)
93
- try:
94
- url = f"{self.base_url}/v1/snapser-api/games"
95
- res = requests.get(
96
- url, headers={'api-key': self.api_key},
97
- timeout=SERVER_CALL_TIMEOUT
98
- )
99
- response_json = res.json()
100
- if res.ok:
101
- if 'games' in response_json:
102
- success(response_json['games'])
103
- return True
104
- error(response_json)
105
- except RequestException as e:
106
- error(f"Exception: Unable to update your snapend {e}")
107
- return False
94
+ )
95
+ progress.start()
96
+ progress.add_task(
97
+ description='Enumerating all your games...', total=None)
98
+ try:
99
+ url = f"{self.base_url}/v1/snapser-api/games"
100
+ res = requests.get(
101
+ url, headers={'api-key': self.api_key},
102
+ timeout=SERVER_CALL_TIMEOUT
103
+ )
104
+ response_json = res.json()
105
+ if res.ok and 'games' in response_json:
106
+ snapctl_success(response_json['games'], progress)
107
+ snapctl_error('Unable to enumerate games.',
108
+ SNAPCTL_GAME_ENUMERATE_ERROR, progress)
109
+ except RequestException as e:
110
+ snapctl_error(f"Exception: Unable to update your snapend {e}",
111
+ SNAPCTL_GAME_ENUMERATE_ERROR, progress)
112
+ snapctl_error('Failed to enumerate games.',
113
+ SNAPCTL_GAME_ENUMERATE_ERROR, progress)
@@ -0,0 +1,93 @@
1
+ """
2
+ Generate CLI commands
3
+ """
4
+ import json
5
+ import os
6
+ from typing import Union
7
+ from rich.progress import Progress, SpinnerColumn, TextColumn
8
+ from snapctl.config.constants import SNAPCTL_INPUT_ERROR, \
9
+ SNAPCTL_GENERATE_GENERIC_ERROR
10
+ from snapctl.config.hashes import BYOSNAP_TEMPLATE
11
+ from snapctl.utils.echo import error
12
+ from snapctl.utils.helper import snapctl_error, snapctl_success
13
+
14
+
15
+ class Generate:
16
+ """
17
+ Generate CLI commands
18
+ """
19
+ SUBCOMMANDS = ['byosnap-profile']
20
+ BYOSNAP_PROFILE_FN = 'snapser-byosnap-profile.json'
21
+
22
+ def __init__(
23
+ self, subcommand: str, base_url: str, api_key: str | None,
24
+ out_path: Union[str, None]
25
+ ) -> None:
26
+ self.subcommand: str = subcommand
27
+ self.base_url: str = base_url
28
+ self.api_key: str = api_key
29
+ self.out_path: Union[str, None] = out_path
30
+ # Validate input
31
+ self.validate_input()
32
+
33
+ # Validator
34
+
35
+ def validate_input(self) -> None:
36
+ """
37
+ Validator
38
+ """
39
+ if self.subcommand not in Generate.SUBCOMMANDS:
40
+ snapctl_error(
41
+ f"Invalid command {self.subcommand}. Valid command are "
42
+ f"{Generate.SUBCOMMANDS}",
43
+ SNAPCTL_INPUT_ERROR
44
+ )
45
+ if self.subcommand in ['byosnap-profile']:
46
+ # Check path
47
+ if self.out_path and not os.path.isdir(self.out_path):
48
+ snapctl_error(
49
+ f"Invalid path {self.out_path}. Wont be able to "
50
+ "store the byosnap-profile.json file",
51
+ SNAPCTL_INPUT_ERROR
52
+ )
53
+
54
+ def byosnap_profile(self) -> None:
55
+ """
56
+ Generate snapser-byosnap-profile.json
57
+ """
58
+ progress = Progress(
59
+ SpinnerColumn(),
60
+ TextColumn("[progress.description]{task.description}"),
61
+ transient=True,
62
+ )
63
+ progress.start()
64
+ progress.add_task(
65
+ description='Promoting your staging snapend...', total=None)
66
+ try:
67
+ if self.out_path is not None:
68
+ file_save_path = os.path.join(
69
+ self.out_path, Generate.BYOSNAP_PROFILE_FN)
70
+ else:
71
+ file_save_path = os.path.join(
72
+ os.getcwd(), Generate.BYOSNAP_PROFILE_FN)
73
+ file_written = False
74
+ with open(file_save_path, "w") as file:
75
+ json.dump(BYOSNAP_TEMPLATE, file, indent=4)
76
+ file_written = True
77
+ if file_written:
78
+ snapctl_success(
79
+ "BYOSNAP Profile generation successful. "
80
+ f"{Generate.BYOSNAP_PROFILE_FN} saved at {file_save_path}",
81
+ progress
82
+ )
83
+ except (IOError, OSError) as file_error:
84
+ snapctl_error(f"File error: {file_error}",
85
+ SNAPCTL_GENERATE_GENERIC_ERROR, progress)
86
+ except json.JSONDecodeError as json_error:
87
+ snapctl_error(f"JSON error: {json_error}",
88
+ SNAPCTL_GENERATE_GENERIC_ERROR, progress)
89
+ snapctl_error(
90
+ "Failed to generate BYOSNAP Profile",
91
+ SNAPCTL_GENERATE_GENERIC_ERROR,
92
+ progress
93
+ )