argenta 0.3.9__tar.gz → 0.4.1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: argenta
3
- Version: 0.3.9
3
+ Version: 0.4.1
4
4
  Summary: python library for creating custom shells
5
5
  License: MIT
6
6
  Author: kolo
@@ -75,12 +75,11 @@ from argenta.command.flag import FlagsGroup, Flag
75
75
 
76
76
  router = Router()
77
77
 
78
- registered_flags = FlagsGroup([
78
+ registered_flags = FlagsGroup(
79
79
  Flag(flag_name='host',
80
80
  flag_prefix='--',
81
81
  possible_flag_values=re.compile(r'^192.168.\d{1,3}.\d{1,3}$')),
82
- Flag('port', '---', re.compile(r'^[0-9]{1,4}$'))
83
- ])
82
+ Flag('port', '--', re.compile(r'^[0-9]{1,4}$')))
84
83
 
85
84
 
86
85
  @router.command(Command("hello"))
@@ -380,8 +379,7 @@ Command(trigger: str,
380
379
  ```python
381
380
  Flag(flag_name: str,
382
381
  flag_prefix: typing.Literal['-', '--', '---'] = '-',
383
- ignore_flag_value_register: bool = False,
384
- possible_flag_values: list[str] | typing.Pattern[str] = False)
382
+ possible_flag_values: list[str] | typing.Pattern[str] | False = True)
385
383
  ```
386
384
 
387
385
  ---
@@ -390,9 +388,10 @@ Flag(flag_name: str,
390
388
  - **name : mean**
391
389
  - `flag_name` (`str`): Имя флага
392
390
  - `flag_prefix` (`Literal['-', '--', '---']`): Префикс команды, допустимым значением является от одного до трёх минусов
393
- - `ignore_flag_value_register` (`bool`): Будет ли игнорироваться регистр значения введённого флага
394
- - `possible_flag_values` (`list[str] | Pattern[str]`): Множество допустимых значений флага, может быть задано
395
- списком с допустимыми значениями или регулярным выражением (рекомендуется `re.compile(r'example exspression')`)
391
+ - `possible_flag_values` (`list[str] | Pattern[str] | bool`): Множество допустимых значений флага, может быть задано
392
+ списком с допустимыми значениями или регулярным выражением (рекомендуется `re.compile(r'example exspression')`), при значении
393
+ аргумента `False` у введённого флага не может быть значения, иначе будет вызвано исключение и обработано соответствующим
394
+ еррор-хэндлером
396
395
 
397
396
  ---
398
397
 
@@ -425,14 +424,14 @@ Flag(flag_name: str,
425
424
 
426
425
  ### Конструктор
427
426
  ```python
428
- FlagsGroup(flags: list[Flag] = None)
427
+ FlagsGroup(*flagы: Flag)
429
428
  ```
430
429
 
431
430
  ---
432
431
 
433
432
  **Аргументы:**
434
433
  - **name : mean**
435
- - `flags` (`list[Flag]`): Список флагов, которые будут объединены в одну группу
434
+ - `*flags` (`Flag`): Неограниченное количество передаваемых флагов
436
435
 
437
436
  ---
438
437
 
@@ -60,12 +60,11 @@ from argenta.command.flag import FlagsGroup, Flag
60
60
 
61
61
  router = Router()
62
62
 
63
- registered_flags = FlagsGroup([
63
+ registered_flags = FlagsGroup(
64
64
  Flag(flag_name='host',
65
65
  flag_prefix='--',
66
66
  possible_flag_values=re.compile(r'^192.168.\d{1,3}.\d{1,3}$')),
67
- Flag('port', '---', re.compile(r'^[0-9]{1,4}$'))
68
- ])
67
+ Flag('port', '--', re.compile(r'^[0-9]{1,4}$')))
69
68
 
70
69
 
71
70
  @router.command(Command("hello"))
@@ -365,8 +364,7 @@ Command(trigger: str,
365
364
  ```python
366
365
  Flag(flag_name: str,
367
366
  flag_prefix: typing.Literal['-', '--', '---'] = '-',
368
- ignore_flag_value_register: bool = False,
369
- possible_flag_values: list[str] | typing.Pattern[str] = False)
367
+ possible_flag_values: list[str] | typing.Pattern[str] | False = True)
370
368
  ```
371
369
 
372
370
  ---
@@ -375,9 +373,10 @@ Flag(flag_name: str,
375
373
  - **name : mean**
376
374
  - `flag_name` (`str`): Имя флага
377
375
  - `flag_prefix` (`Literal['-', '--', '---']`): Префикс команды, допустимым значением является от одного до трёх минусов
378
- - `ignore_flag_value_register` (`bool`): Будет ли игнорироваться регистр значения введённого флага
379
- - `possible_flag_values` (`list[str] | Pattern[str]`): Множество допустимых значений флага, может быть задано
380
- списком с допустимыми значениями или регулярным выражением (рекомендуется `re.compile(r'example exspression')`)
376
+ - `possible_flag_values` (`list[str] | Pattern[str] | bool`): Множество допустимых значений флага, может быть задано
377
+ списком с допустимыми значениями или регулярным выражением (рекомендуется `re.compile(r'example exspression')`), при значении
378
+ аргумента `False` у введённого флага не может быть значения, иначе будет вызвано исключение и обработано соответствующим
379
+ еррор-хэндлером
381
380
 
382
381
  ---
383
382
 
@@ -410,14 +409,14 @@ Flag(flag_name: str,
410
409
 
411
410
  ### Конструктор
412
411
  ```python
413
- FlagsGroup(flags: list[Flag] = None)
412
+ FlagsGroup(*flagы: Flag)
414
413
  ```
415
414
 
416
415
  ---
417
416
 
418
417
  **Аргументы:**
419
418
  - **name : mean**
420
- - `flags` (`list[Flag]`): Список флагов, которые будут объединены в одну группу
419
+ - `*flags` (`Flag`): Неограниченное количество передаваемых флагов
421
420
 
422
421
  ---
423
422
 
@@ -1,11 +1,11 @@
1
- from pprint import pprint
2
1
  from typing import Callable
3
2
  from inspect import getfullargspec
4
3
  import re
5
4
 
6
- from ..command.entity import Command
7
- from ..router.entity import Router
8
- from ..command.exceptions import (UnprocessedInputFlagException,
5
+ from argenta.command import Command
6
+ from argenta.router import Router
7
+ from argenta.router.defaults import system_router
8
+ from argenta.command.exceptions import (UnprocessedInputFlagException,
9
9
  RepeatedInputFlagsException,
10
10
  EmptyInputCommandException)
11
11
  from .exceptions import (InvalidRouterInstanceException,
@@ -30,6 +30,7 @@ class App:
30
30
  line_separate: str = '',
31
31
  command_group_description_separate: str = '',
32
32
  repeat_command_groups: bool = True,
33
+ messages_on_startup: list[str] = None,
33
34
  print_func: Callable[[str], None] = print) -> None:
34
35
  self.prompt = prompt
35
36
  self.print_func = print_func
@@ -44,6 +45,7 @@ class App:
44
45
  self.command_group_description_separate = command_group_description_separate
45
46
  self.ignore_command_register = ignore_command_register
46
47
  self.repeat_command_groups = repeat_command_groups
48
+ self.messages_on_startup = messages_on_startup if messages_on_startup else []
47
49
 
48
50
  self._routers: list[Router] = []
49
51
  self._description_message_pattern: str = '[{command}] *=*=* {description}'
@@ -51,16 +53,21 @@ class App:
51
53
  self._invalid_input_flags_handler: Callable[[str], None] = lambda raw_command: print_func(f'Incorrect flag syntax: "{raw_command}"')
52
54
  self._repeated_input_flags_handler: Callable[[str], None] = lambda raw_command: print_func(f'Repeated input flags: "{raw_command}"')
53
55
  self._empty_input_command_handler: Callable[[], None] = lambda: print_func(f'Empty input command')
54
- self._unknown_command_handler: Callable[[Command], None] = lambda command: print_func(f"Unknown command: {command.get_string_entity()}")
56
+ self._unknown_command_handler: Callable[[Command], None] = lambda command: print_func(f"Unknown command: {command.get_trigger()}")
57
+ self._exit_command_handler: Callable[[], None] = lambda: print_func(self.farewell_message)
55
58
 
56
59
 
57
60
  def start_polling(self) -> None:
61
+ self._setup_system_router()
58
62
  self._validate_number_of_routers()
59
63
  self._validate_included_routers()
60
64
  self._validate_all_router_commands()
61
65
 
62
66
  self.print_func(self.initial_message)
63
67
 
68
+ for message in self.messages_on_startup:
69
+ self.print_func(message)
70
+
64
71
  if not self.repeat_command_groups:
65
72
  self._print_command_group_description()
66
73
  self.print_func(self.prompt)
@@ -101,7 +108,9 @@ class App:
101
108
  self.print_func(self.prompt)
102
109
  continue
103
110
 
104
- self._check_command_for_exit_command(input_command.get_trigger())
111
+ is_exit = self._is_exit_command(input_command)
112
+ if is_exit:
113
+ return
105
114
 
106
115
  self.print_func(self.line_separate)
107
116
  is_unknown_command: bool = self._check_is_command_unknown(input_command)
@@ -172,6 +181,18 @@ class App:
172
181
  self._empty_input_command_handler = handler
173
182
 
174
183
 
184
+ def set_exit_command_handler(self, handler: Callable[[], None]) -> None:
185
+ args = getfullargspec(handler).args
186
+ if len(args) != 0:
187
+ raise IncorrectNumberOfHandlerArgsException()
188
+ else:
189
+ self._exit_command_handler = handler
190
+
191
+
192
+ def add_message_on_startup(self, message: str) -> None:
193
+ self.messages_on_startup.append(message)
194
+
195
+
175
196
  def include_router(self, router: Router) -> None:
176
197
  if not isinstance(router, Router):
177
198
  raise InvalidRouterInstanceException()
@@ -213,15 +234,26 @@ class App:
213
234
  raise RepeatedCommandInDifferentRoutersException()
214
235
 
215
236
 
216
- def _check_command_for_exit_command(self, command: str):
217
- if command.lower() == self.exit_command.lower():
237
+ def _setup_system_router(self):
238
+ system_router.set_title(self.system_points_title)
239
+ @system_router.command(Command(self.exit_command, self.exit_command_description))
240
+ def exit_command():
241
+ self._exit_command_handler()
242
+
243
+ if system_router not in [router['entity'] for router in self._registered_router_entities]:
244
+ self.include_router(system_router)
245
+
246
+
247
+ def _is_exit_command(self, command: Command):
248
+ if command.get_trigger().lower() == self.exit_command.lower():
218
249
  if self.ignore_exit_command_register:
219
- self.print_func(self.farewell_message)
220
- exit(0)
250
+ system_router.input_command_handler(command)
251
+ return True
221
252
  else:
222
- if command == self.exit_command:
223
- self.print_func(self.farewell_message)
224
- exit(0)
253
+ if command.get_trigger() == self.exit_command:
254
+ system_router.input_command_handler(command)
255
+ return True
256
+ return False
225
257
 
226
258
 
227
259
  def _check_is_command_unknown(self, command: Command):
@@ -248,12 +280,3 @@ class App:
248
280
  )
249
281
  )
250
282
  self.print_func(self.command_group_description_separate)
251
-
252
- self.print_func(self.system_points_title)
253
- self.print_func(self._description_message_pattern.format(
254
- command=self.exit_command,
255
- description=self.exit_command_description
256
- )
257
- )
258
- self.print_func(self.command_group_description_separate)
259
-
@@ -6,6 +6,7 @@ from .exceptions import (UnprocessedInputFlagException,
6
6
 
7
7
  from typing import Generic, TypeVar, cast, Literal
8
8
 
9
+
9
10
  CommandType = TypeVar('CommandType')
10
11
 
11
12
 
@@ -15,8 +16,7 @@ class Command(Generic[CommandType]):
15
16
  flags: Flag | FlagsGroup = None):
16
17
  self._trigger = trigger
17
18
  self._description = f'description for "{self._trigger}" command' if not description else description
18
- self._registered_flags: FlagsGroup | None = flags if isinstance(flags, FlagsGroup) else FlagsGroup([flags]) if isinstance(flags, Flag) else flags
19
-
19
+ self._registered_flags: FlagsGroup | None = flags if isinstance(flags, FlagsGroup) else FlagsGroup(flags) if isinstance(flags, Flag) else flags
20
20
  self._input_flags: FlagsGroup | None = None
21
21
 
22
22
 
@@ -56,7 +56,7 @@ class Command(Generic[CommandType]):
56
56
  return self._input_flags
57
57
 
58
58
  @staticmethod
59
- def parse_input_command(raw_command: str) -> 'Command[CommandType]':
59
+ def parse_input_command(raw_command: str) -> CommandType:
60
60
  if not raw_command:
61
61
  raise EmptyInputCommandException()
62
62
  list_of_tokens = raw_command.split()
@@ -0,0 +1,21 @@
1
+ from dataclasses import dataclass
2
+ from argenta.command.flag import Flag
3
+ import re
4
+
5
+
6
+ @dataclass
7
+ class DefaultFlags:
8
+ help_flag = Flag(flag_name='help', possible_flag_values=False)
9
+ short_help_flag = Flag(flag_name='h', flag_prefix='-', possible_flag_values=False)
10
+
11
+ info_flag = Flag(flag_name='info', possible_flag_values=False)
12
+ short_info_flag = Flag(flag_name='i', flag_prefix='-', possible_flag_values=False)
13
+
14
+ all_flag = Flag(flag_name='all', possible_flag_values=False)
15
+ short_all_flag = Flag(flag_name='a', flag_prefix='-', possible_flag_values=False)
16
+
17
+ host_flag = Flag(flag_name='host', possible_flag_values=re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'))
18
+ short_host_flag = Flag(flag_name='h', flag_prefix='-', possible_flag_values=re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'))
19
+
20
+ port_flag = Flag(flag_name='port', possible_flag_values=re.compile(r'^\d{1,5}$'))
21
+ short_port_flag = Flag(flag_name='p', flag_prefix='-', possible_flag_values=re.compile(r'^\d{1,5}$'))
@@ -1,4 +1,4 @@
1
- from argenta.command.flag.entity import Flag
1
+ from argenta.command.flag import Flag
2
2
 
3
3
 
4
4
  class FlagsGroup:
@@ -0,0 +1,5 @@
1
+ from argenta.router import Router
2
+
3
+
4
+ system_router = Router(title='System points:',
5
+ name='System')
@@ -23,7 +23,7 @@ class Router:
23
23
  self._command_entities: list[dict[str, Callable[[], None] | Command]] = []
24
24
  self._ignore_command_register: bool = False
25
25
 
26
- self._not_valid_flag_handler: Callable[[Flag], None] = lambda flag: print(f"Undefined or incorrect input flag: '{flag.get_string_entity()} {flag.get_value()}'")
26
+ self._not_valid_flag_handler: Callable[[Flag], None] = lambda flag: print(f"Undefined or incorrect input flag: {flag.get_string_entity()}{(' '+flag.get_value()) if flag.get_value() else ''}")
27
27
 
28
28
 
29
29
  def command(self, command: Command) -> Callable[[Any], Any]:
@@ -116,6 +116,10 @@ class Router:
116
116
  return self._title
117
117
 
118
118
 
119
+ def set_title(self, title: str):
120
+ self._title = title
121
+
122
+
119
123
  def get_all_commands(self) -> list[str]:
120
124
  all_commands: list[str] = []
121
125
  for command_entity in self._command_entities:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "argenta"
3
- version = "0.3.9"
3
+ version = "0.4.1"
4
4
  description = "python library for creating custom shells"
5
5
  authors = [
6
6
  {name = "kolo", email = "kolo.is.main@gmail.com"}
@@ -1,18 +0,0 @@
1
- from argenta.command.flag import Flag
2
- import re
3
-
4
-
5
- help_flag = Flag(flag_name='help', possible_flag_values=False)
6
- short_help_flag = Flag(flag_name='h', flag_prefix='-', possible_flag_values=False)
7
-
8
- info_flag = Flag(flag_name='info', possible_flag_values=False)
9
- short_info_flag = Flag(flag_name='i', flag_prefix='-', possible_flag_values=False)
10
-
11
- all_flag = Flag(flag_name='all', possible_flag_values=False)
12
- short_all_flag = Flag(flag_name='a', flag_prefix='-', possible_flag_values=False)
13
-
14
- host_flag = Flag(flag_name='host', possible_flag_values=re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'))
15
- short_host_flag = Flag(flag_name='h', flag_prefix='-', possible_flag_values=re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'))
16
-
17
- port_flag = Flag(flag_name='port', possible_flag_values=re.compile(r'^\d{1,5}$'))
18
- short_port_flag = Flag(flag_name='p', flag_prefix='-', possible_flag_values=re.compile(r'^\d{1,5}$'))
File without changes
File without changes
File without changes