MainShortcuts2 2.10.1__tar.gz → 2.10.3__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.
Files changed (62) hide show
  1. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/PKG-INFO +1 -1
  2. mainshortcuts2-2.10.3/pyproject.toml +54 -0
  3. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/__main__.py +28 -0
  4. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/_module_info.py +1 -1
  5. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/sqlite_ex.py +15 -5
  6. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/java_launch/__init__.py +9 -10
  7. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/java_launch/infofile.py +71 -7
  8. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ms2hash.py +13 -2
  9. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/sql/_sql_base.py +35 -18
  10. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/sql/sqlite.py +5 -0
  11. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/types.py +44 -0
  12. mainshortcuts2-2.10.1/pyproject.toml +0 -52
  13. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/README.md +0 -0
  14. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/__init__.py +0 -0
  15. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/_any2json_regs.py +0 -0
  16. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/_ms2app_regs.py +0 -0
  17. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/_ms2dat_auto.py +0 -0
  18. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/advanced.py +0 -0
  19. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/any2json.py +0 -0
  20. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/api/base.py +0 -0
  21. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/api/gigachat.py +0 -0
  22. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/api/github.py +0 -0
  23. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/api/russian_trusted_root_ca_pem.crt +0 -0
  24. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/api/russian_trusted_sub_ca_pem.crt +0 -0
  25. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/api/webdav.py +0 -0
  26. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/cfg.py +0 -0
  27. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/core.py +0 -0
  28. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/core_config.py +0 -0
  29. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/dict.py +0 -0
  30. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/dir.py +0 -0
  31. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/__init__.py +0 -0
  32. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/aiohttp_ex/web/__init__.py +0 -0
  33. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/aiohttp_ex/web/__main__.py +0 -0
  34. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/datetime_ex.py +0 -0
  35. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/pathlib_ex.py +0 -0
  36. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/pil_ex.py +0 -0
  37. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/psutil_ex.py +0 -0
  38. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ex/urlparse_ex.py +0 -0
  39. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/file.py +0 -0
  40. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/gui_scripts/__init__.py +0 -0
  41. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/gui_scripts/ms2_hash_gen.py +0 -0
  42. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/gui_scripts/utils.py +0 -0
  43. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/java_ext/__init__.py +0 -0
  44. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/java_ext/ms2ext.py +0 -0
  45. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/java_launch/__main__.py +0 -0
  46. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/java_launch/util.py +0 -0
  47. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/json.py +0 -0
  48. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/linux.py +0 -0
  49. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/list.py +0 -0
  50. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ms2app.py +0 -0
  51. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ms2dat1.py +0 -0
  52. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/ms2dat1crypto.py +0 -0
  53. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/path.py +0 -0
  54. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/proc.py +0 -0
  55. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/regex.py +0 -0
  56. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/special_chars.py +0 -0
  57. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/sql/mysql.py +0 -0
  58. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/sql/postgresql.py +0 -0
  59. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/str.py +0 -0
  60. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/term.py +0 -0
  61. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/utils.py +0 -0
  62. {mainshortcuts2-2.10.1 → mainshortcuts2-2.10.3}/src/MainShortcuts2/win.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MainShortcuts2
3
- Version: 2.10.1
3
+ Version: 2.10.3
4
4
  Summary: Сокращение и улучшение функций + консольные утилиты
5
5
  Author: MainPlay TG
6
6
  Author-email: xbox.roman6666666666@gmail.com
@@ -0,0 +1,54 @@
1
+ [tool.poetry]
2
+ version = "2.10.3"
3
+ name = "MainShortcuts2"
4
+ description = "Сокращение и улучшение функций + консольные утилиты"
5
+ authors = ["MainPlay TG <xbox.roman6666666666@gmail.com>"]
6
+ readme = "README.md"
7
+ repository = "https://github.com/MainPlay-TG/MainShortcuts2.py"
8
+ packages = [
9
+ {include= "MainShortcuts2", from = "src"},
10
+ ]
11
+
12
+ [tool.poetry.scripts]
13
+ "micro-json" = "MainShortcuts2.__main__:micro_json"
14
+ "ms2-app" = "MainShortcuts2.ms2app:main"
15
+ "ms2-hash_check" = "MainShortcuts2.ms2hash:hash_check"
16
+ "ms2-hash_gen" = "MainShortcuts2.ms2hash:hash_gen"
17
+ "ms2-hash_java" = "MainShortcuts2.ms2hash:run_java_ext"
18
+ "ms2sign" = "MainShortcuts2.ms2hash:run_ms2sign"
19
+ "ms2-import_example" = "MainShortcuts2.__main__:import_example"
20
+ "ms2-ln" = "MainShortcuts2.__main__:ln"
21
+ "ms2-which_real" = "MainShortcuts2.__main__:which_real"
22
+ "nano-json" = "MainShortcuts2.__main__:nano_json"
23
+ "nginx-reload" = "MainShortcuts2.__main__:nginx_reload"
24
+ "nginx-restart" = "MainShortcuts2.__main__:nginx_restart"
25
+ "ms2java-launch" = "MainShortcuts2.java_launch.__main__:launch"
26
+ "ms2java-info" = "MainShortcuts2.java_launch.__main__:print_info"
27
+ "ms2-random" = "MainShortcuts2.__main__:rand"
28
+
29
+ [tool.poetry.dependencies]
30
+ python = "^3.10"
31
+
32
+ # Любые синхронные функции с использованием HTTP
33
+ requests = {version = "^2.32.5", optional = true}
34
+
35
+ # ms2dat1crypto
36
+ cryptography = {version = "^50.0.0", optional = true}
37
+
38
+ # Все прочие необязательные зависимости
39
+ aiohttp = {version = "^3.14.3", optional = true}
40
+ colorama = {version = "^0.4.6", optional = true}
41
+ json5 = {version = "^0.15.0", optional = true}
42
+ pillow = {version = "^12.3.0", optional = true}
43
+ progressbar2 = {version = "^4.6.0", optional = true}
44
+ psutil = {version = "^7.2.2", optional = true}
45
+ pyside6 = {version = "^6.11.2", optional = true}
46
+
47
+ [tool.poetry.extras]
48
+ crypto = ["cryptography"]
49
+ full = ["aiohttp", "colorama", "cryptography", "json5", "pillow", "progressbar2", "psutil", "pyside6", "requests"]
50
+ http = ["requests"]
51
+
52
+ ["build-system"]
53
+ "build-backend" = "poetry.core.masonry.api"
54
+ requires = ["poetry-core"]
@@ -1,4 +1,5 @@
1
1
  import argparse
2
+ import base64
2
3
  import os
3
4
  import sys
4
5
  from MainShortcuts2 import ms
@@ -166,3 +167,30 @@ def which_real(args=None, **kw):
166
167
  code = 2
167
168
  log("Failed to create symbolic link: %r", exc)
168
169
  sys.exit(code)
170
+
171
+
172
+ def rand(args=None):
173
+ if args is None:
174
+ argp = argparse.ArgumentParser("ms2-random")
175
+ argp.description = "Генератор случайных данных"
176
+ argp.add_argument("-t", "--type", default="b64url", help="тип выходных данных. По умолчанию base64urlsafe")
177
+ argp.add_argument("size", type=int, default=32, nargs="?", help="размер выходной строки")
178
+ args = argp.parse_args()
179
+ raw = os.urandom(args.size)
180
+ t = str(args.type).lower()
181
+ if t in ("base64", "b64"):
182
+ sys.stdout.buffer.write(base64.b64encode(raw)[:args.size])
183
+ elif t in ("base64urlsafe", "base64url", "b64urlsafe", "b64url"):
184
+ sys.stdout.buffer.write(base64.urlsafe_b64encode(raw)[:args.size])
185
+ elif t in ("bytes", "raw"):
186
+ sys.stdout.buffer.write(raw)
187
+ elif t == "hex":
188
+ sys.stdout.write(raw.hex()[:args.size])
189
+ else:
190
+ print(f"Неизвестный тип: {t}", file=sys.stderr)
191
+ print("Допустимые типы:", file=sys.stderr)
192
+ print(" base64, b64", file=sys.stderr)
193
+ print(" base64urlsafe, base64url, b64urlsafe, b64url", file=sys.stderr)
194
+ print(" bytes, raw", file=sys.stderr)
195
+ print(" hex", file=sys.stderr)
196
+ sys.exit(1)
@@ -1,2 +1,2 @@
1
1
  name = 'mainshortcuts2'
2
- version = '2.10.1'
2
+ version = '2.10.3'
@@ -38,10 +38,12 @@ def make_insert_sql(table: str, values: dict, modifier=""):
38
38
 
39
39
 
40
40
  def make_select_sql(table: str, columns: str | list[str], where: dict):
41
- text, params = make_where_string(where)
42
41
  if not isinstance(columns, str):
43
42
  columns = ','.join(columns)
44
- return f"SELECT {columns} FROM {table} WHERE {text};", params
43
+ if where:
44
+ text, params = make_where_string(where)
45
+ return f"SELECT {columns} FROM {table} WHERE {text};", params
46
+ return f"SELECT {columns} FROM {table};", []
45
47
 
46
48
 
47
49
  def make_update_sql(table: str, values: dict, where: dict):
@@ -80,13 +82,13 @@ class Cursor(sqlite3.Cursor):
80
82
  """Вставить строку в таблицу"""
81
83
  return self.execute(*make_insert_sql(table, values))
82
84
 
83
- def select_fetchall(self, table: str, columns: list[str], where: dict):
85
+ def select_fetchall(self, table: str, columns: list[str], where: dict = None):
84
86
  return self.select(table, columns, where).fetchall()
85
87
 
86
- def select_fetchone(self, table: str, columns: list[str], where: dict):
88
+ def select_fetchone(self, table: str, columns: list[str], where: dict = None):
87
89
  return self.select(table, columns, where).fetchone()
88
90
 
89
- def select(self, table: str, columns: str | list[str], where: dict):
91
+ def select(self, table: str, columns: str | list[str], where: dict = None):
90
92
  """Выбрать строки из таблицы. Не выполняет `fetch`!"""
91
93
  return self.execute(*make_select_sql(table, columns, where))
92
94
 
@@ -96,6 +98,10 @@ class Cursor(sqlite3.Cursor):
96
98
  return self
97
99
  return self.execute(*make_update_sql(table, values, where))
98
100
 
101
+ def select_count(self, table: str, where: dict = None) -> int:
102
+ """Выбрать кол-во строк"""
103
+ return self.select_fetchone(table, "COUNT(*)", where)[0]
104
+
99
105
 
100
106
  class Connection(sqlite3.Connection):
101
107
  @classmethod
@@ -150,6 +156,10 @@ class Connection(sqlite3.Connection):
150
156
  with self.cursor() as cur:
151
157
  cur.update(table, values, where)
152
158
 
159
+ def select_count(self, table: str, where: dict = None):
160
+ with self.cursor() as cur:
161
+ return cur.select_count(table, where)
162
+
153
163
 
154
164
  connect = Connection.connect
155
165
  create_in_memory = Connection.create_in_memory
@@ -40,20 +40,19 @@ class JavaLaunchManager:
40
40
 
41
41
  def download_depends(self, clazz: _ClassInfo, download_optional=False):
42
42
  """Скачать зависимости класса"""
43
- queue: set[tuple[str, Path]] = set()
44
- for i in clazz.required_depends:
43
+ depends = clazz.required_depends.copy()
44
+ if download_optional:
45
+ depends.update(clazz.optional_depends)
46
+ for i in list(depends):
47
+ depends.update(i.recursive_dependencies)
48
+ queue: dict[str, Path] = {}
49
+ for i in depends:
45
50
  file = self.cache_root / i.file_name
46
51
  if not file.exists():
47
52
  file.parent.any_mkdir()
48
- queue.add((i.file_url, file))
49
- if download_optional:
50
- for i in clazz.optional_depends:
51
- file = self.cache_root / i.file_name
52
- if not file.exists():
53
- file.parent.any_mkdir()
54
- queue.add((i.file_url, file))
53
+ queue[i.file_url] = file
55
54
  with ThreadPoolExecutor() as pool:
56
- futures = [pool.submit(self.downloader.download2file, *i) for i in queue]
55
+ futures = [pool.submit(self.downloader.download2file, url, path) for url, path in queue.items()]
57
56
  [i.result() for i in futures]
58
57
 
59
58
  def launch_file(self, file: Path, args: list[str] = [], *,
@@ -1,8 +1,10 @@
1
1
  import hashlib
2
2
  import os
3
+ import sys
3
4
  from functools import cached_property
4
5
  from MainShortcuts2.ex.pathlib_ex import Path
5
6
  from MainShortcuts2.utils import short_urlsafe_b64encode
7
+ from xml.etree import ElementTree
6
8
  _rand = os.urandom(8)
7
9
 
8
10
 
@@ -20,26 +22,35 @@ class _ClassInfo(dict):
20
22
  """Необязательные зависимости"""
21
23
  self.required_names: set[str] = set(self.get("required") or [])
22
24
  """Обязательные зависимости"""
25
+
23
26
  @property
24
27
  def optional_depends(self):
25
- return {self._root.dependencies[i] for i in self.optional_names}
28
+ deps = {self._root.dependencies[i] for i in self.optional_names}
29
+ return {i for i in deps if i.need_to_install}
26
30
 
27
31
  @property
28
32
  def required_depends(self):
29
- return {*self._root.required_dependencies, *[self._root.dependencies[i] for i in self.required_names]}
33
+ deps = {*self._root.required_dependencies, *[self._root.dependencies[i] for i in self.required_names]}
34
+ return {i for i in deps if i.need_to_install}
35
+
36
+ def _get_files(self, cache_root: Path, dep: "set[_Dependency]"):
37
+ files: set[Path] = set()
38
+ for i in dep:
39
+ files.add(cache_root / i.file_name)
40
+ for i2 in i.recursive_dependencies:
41
+ files.add(cache_root / i2.file_name)
42
+ return files
30
43
 
31
44
  def build_args(self, cache_root: Path, file: Path):
32
45
  """Собрать список аргументов. Без пути к Java и пользовательских аргументов"""
33
46
  cp = {str(file), }
34
47
  # Собрать обязательные зависимости
35
- for i in self.required_depends:
36
- file = cache_root / i.file_name
48
+ for file in self._get_files(cache_root, self.required_depends):
37
49
  if not file.exists():
38
50
  raise FileNotFoundError(file)
39
51
  cp.add(str(file))
40
52
  # Собрать необязательные зависимости
41
- for i in self.optional_depends:
42
- file = cache_root / i.file_name
53
+ for file in self._get_files(cache_root, self.optional_depends):
43
54
  if file.exists():
44
55
  cp.add(str(file))
45
56
  return [*self.java_args, "-cp", os.path.pathsep.join(cp), self.name]
@@ -61,6 +72,15 @@ class _Dependency(dict):
61
72
  """Требуется ли для всего JAR"""
62
73
  self.size: int | None = self.get("size")
63
74
  self.version: str = self["version"]
75
+ self.platforms: set[str] = set(self.get("platforms") or [])
76
+
77
+ @property
78
+ def need_to_install(self):
79
+ # Если список пуст - всегда требуется
80
+ if self.platforms:
81
+ if sys.platform not in self.platforms:
82
+ return False
83
+ return True
64
84
 
65
85
  def __hash__(self):
66
86
  return hash(f"{_rand}_{self.file_url}")
@@ -83,15 +103,51 @@ class _Dependency(dict):
83
103
  """URL для скачивания файла"""
84
104
  return f"{self.repository_url}/{self.group.replace(".", "/")}/{self.artifact}/{self.version}/{self.artifact}-{self.version}{self.classifier}.{self.ext}"
85
105
 
106
+ @cached_property
107
+ def dependencies(self) -> "set[_Dependency]":
108
+ from . import manager
109
+ pom_file = (manager.cache_root / self.file_name).with_name(f"{self.artifact}-{self.version}.pom")
110
+ if not pom_file.exists():
111
+ pom_file.parent.any_mkdir()
112
+ pom_url = f"{self.repository_url}/{self.group.replace(".", "/")}/{self.artifact}/{self.version}/{self.artifact}-{self.version}.pom"
113
+ manager.downloader.download2file(pom_url, pom_file)
114
+ et = ElementTree.parse(pom_file).getroot()
115
+ result = set()
116
+ for rootItem in et:
117
+ if rootItem.tag.endswith("dependencies"):
118
+ for depItem in rootItem:
119
+ if depItem.tag.endswith("dependency"):
120
+ data = {"scope": "compile"}
121
+ for metaItem in depItem:
122
+ if metaItem.text:
123
+ if metaItem.tag.endswith("artifactId"):
124
+ data["artifact"] = metaItem.text
125
+ if metaItem.tag.endswith("groupId"):
126
+ data["group"] = metaItem.text
127
+ for k in ("classifier", "scope", "version"):
128
+ if metaItem.tag.endswith(k):
129
+ data[k] = metaItem.text
130
+ if all(data.get(i) for i in ("group", "artifact", "version")) and data["scope"] in ("compile", "runtime"):
131
+ result.add(self._root._get_depend(data))
132
+ return result
133
+
134
+ @cached_property
135
+ def recursive_dependencies(self) -> "set[_Dependency]":
136
+ result = self.dependencies.copy()
137
+ for i in list(result):
138
+ result.update(i.recursive_dependencies)
139
+ return result
140
+
86
141
 
87
142
  class InfoFile(dict):
88
143
  """Информация для запуска JAR"""
89
144
 
90
145
  def __init__(self, map):
91
146
  super().__init__(map)
147
+ self._depend_cache: dict[str, _Dependency] = {}
92
148
  self.classes: dict[str, _ClassInfo] = {k: _ClassInfo(self, v) for k, v in self["classes"].items()}
93
149
  """Все доступные для запуска классы"""
94
- self.dependencies: dict[str, _Dependency] = {k: _Dependency(self, v) for k, v in (self.get("dependencies") or {}).items()}
150
+ self.dependencies: dict[str, _Dependency] = {k: self._get_depend(v) for k, v in (self.get("dependencies") or {}).items()}
95
151
  """Список зависимостей (`alias:info`)"""
96
152
  self.format: int = self["format"]
97
153
  """Формат файла"""
@@ -101,6 +157,14 @@ class InfoFile(dict):
101
157
  """Название основного класса"""
102
158
  self.repositories: dict[str, str] = {k: v.rstrip("/") for k, v in (self.get("repositories") or {})}
103
159
  """Список дополнительных репозиториев (`name:url`)"""
160
+
161
+ def _get_depend(self, map):
162
+ """Кэширование зависимостей чтобы избежать повторного скачивания POM файлов"""
163
+ depend = _Dependency(self, map)
164
+ if depend.file_url not in self._depend_cache:
165
+ self._depend_cache[depend.file_url] = depend
166
+ return self._depend_cache[depend.file_url]
167
+
104
168
  @property
105
169
  def main_class(self):
106
170
  """Основной класс"""
@@ -144,7 +144,7 @@ def hash_check(args=None):
144
144
  completed.append(file)
145
145
 
146
146
 
147
- def run_java_ext(argv: list[str] = None):
147
+ def run_java_ext(argv: list[str] = None, **kw):
148
148
  if argv is None:
149
149
  argv = sys.argv[1:]
150
150
  from MainShortcuts2 import java_ext
@@ -153,11 +153,22 @@ def run_java_ext(argv: list[str] = None):
153
153
  if ver is None:
154
154
  ms.utils.mini_log("Ошибка: не удалось найти версию MS2Hash. Проверьте соединение с GitHub")
155
155
  sys.exit(1)
156
+ if ver.version_name in ("1.0.0", "1.0.1"):
157
+ try:
158
+ ver = mgr.latest_online_version()
159
+ except Exception as exc:
160
+ ms.utils.mini_log("Не удалось обновить MS2Hash: %r", exc)
156
161
  if ver.version_name in ("1.0.0", "1.0.1"):
157
162
  # Старые версии не совместимы с новым лаунчером
158
163
  p = ver.run(argv, check=False)
159
164
  else:
160
165
  # Использовать новый лаунчер
161
166
  from MainShortcuts2 import java_launch
162
- p = java_launch.manager.launch_file(ver.jar_path, argv)
167
+ if ("-b" in argv) or ("--bar" in argv):
168
+ kw["download_optional"] = True
169
+ p = java_launch.manager.launch_file(ver.jar_path, argv, **kw)
163
170
  sys.exit(p.returncode)
171
+
172
+
173
+ def run_ms2sign(argv: list[str] = None):
174
+ run_java_ext(argv, class_name="ms2sign")
@@ -3,6 +3,7 @@ import random
3
3
  import typing
4
4
  import uuid as uuid_module
5
5
  from functools import cached_property
6
+ from MainShortcuts2.types import LRUDictWithRefresh
6
7
  from threading import Lock
7
8
  T = typing.TypeVar("T")
8
9
 
@@ -13,10 +14,10 @@ def check_type(obj, cls: type[T], allow_None=True):
13
14
  return
14
15
  if isinstance(obj, cls):
15
16
  return obj
16
- err_text = "Object %r must be like %r"
17
+ err_text = f"Object {obj!r} must be like {cls!r}"
17
18
  if allow_None:
18
19
  err_text += " or None"
19
- raise ValueError(err_text % (obj, cls))
20
+ raise ValueError(err_text)
20
21
 
21
22
 
22
23
  def _conv_val(value: T) -> T:
@@ -29,13 +30,13 @@ def _conv_row(row: list[T]):
29
30
  return tuple(map(_conv_val, row))
30
31
 
31
32
 
32
- def _gtn(obj: "TABLE_NAME"):
33
+ def _gtn(table: "TABLE_NAME"):
33
34
  """Получить имя таблицы из объекта"""
34
- if isinstance(obj, str):
35
- return obj
36
- if isinstance(obj, ObjectBase) or issubclass(obj, ObjectBase):
37
- return obj._table
38
- raise TypeError("obj must be str or ObjectBase")
35
+ if isinstance(table, str):
36
+ return table
37
+ if isinstance(table, ObjectBase) or issubclass(table, ObjectBase):
38
+ return table._table
39
+ raise TypeError("table must be str or ObjectBase")
39
40
 
40
41
 
41
42
  class ObjectBase:
@@ -57,7 +58,7 @@ class ObjectBase:
57
58
  """Функция вызывается после инициализации объекта"""
58
59
  pass
59
60
 
60
- def __repr__(self) -> str:
61
+ def __repr__(self):
61
62
  cls = type(self)
62
63
  kwargs = []
63
64
  for k, v in self._index.items():
@@ -93,20 +94,27 @@ class ObjectBase:
93
94
  for i in data:
94
95
  if i in self._index:
95
96
  self._index = data[i]
97
+ self._clear_cache(*data.keys())
96
98
 
97
99
  def delete_from_db(self):
98
100
  """Полностью удалить объект из базы данных"""
99
101
  self._db.delete(self._table, self._index)
100
102
 
103
+ def _clear_cache(self, *keys, ignore_cls=False):
104
+ """Сбросить все :class:`cached_property`"""
105
+ cls = type(self)
106
+ if keys:
107
+ for i in keys:
108
+ if ignore_cls or isinstance(getattr(cls, i), cached_property):
109
+ self.__dict__.pop(i, None)
110
+ else:
111
+ for i in dir(cls):
112
+ if (not i.startswith("__")) and isinstance(getattr(cls, i), cached_property):
113
+ self.__dict__.pop(i, None)
114
+
101
115
 
102
116
  TABLE_NAME = str | ObjectBase | type[ObjectBase]
103
117
  gen_uuid = uuid_module.uuid4
104
- if not typing.TYPE_CHECKING:
105
- for i in (8, 7):
106
- j = f"uuid{i}"
107
- if hasattr(uuid_module, j):
108
- gen_uuid = getattr(uuid_module, j)
109
- break
110
118
 
111
119
 
112
120
  class UuidObjectBase(ObjectBase):
@@ -118,6 +126,11 @@ class UuidObjectBase(ObjectBase):
118
126
  if self._enable_cache:
119
127
  self._db.cache[self._table][self.uuid_bytes] = self
120
128
 
129
+ def __eq__(self, other):
130
+ if isinstance(other, UuidObjectBase):
131
+ return self._table == other._table and self.uuid_bytes == other.uuid_bytes
132
+ return super().__eq__(other)
133
+
121
134
  @cached_property
122
135
  def uuid_bytes(self) -> bytes:
123
136
  """Сырой UUID из БД"""
@@ -156,7 +169,7 @@ class UuidObjectBase(ObjectBase):
156
169
  return cls(db, uuid)
157
170
 
158
171
 
159
- if typing.TYPE_CHECKING:
172
+ if typing.TYPE_CHECKING and 0:
160
173
  class CacheDict(typing.Dict[str, typing.Dict[typing.Any, ObjectBase]]):
161
174
  """Словарь для кэширования объектов"""
162
175
  pass
@@ -164,7 +177,7 @@ else:
164
177
  class CacheDict(dict):
165
178
  def __getitem__(self, key) -> dict:
166
179
  if key not in self:
167
- self[key] = {}
180
+ self[key] = LRUDictWithRefresh(256)
168
181
  return super().__getitem__(key)
169
182
 
170
183
 
@@ -284,7 +297,7 @@ class DatabaseBase:
284
297
  if len(results) > 1:
285
298
  raise OverflowError(f"Too many objects found in table {table}")
286
299
  return results[0]
287
- # Рекомендуеться переопределить для оптимизации
300
+ # Рекомендуется переопределить для оптимизации
288
301
 
289
302
  def select_count(self, table: TABLE_NAME, where: dict):
290
303
  """Получить кол-во объектов в таблице"""
@@ -351,3 +364,7 @@ class SyncDatabaseBase(DatabaseBase):
351
364
  def update(self, table, values, where):
352
365
  with self._edit_lock:
353
366
  return super().update(table, values, where)
367
+
368
+ def delete(self, table, where):
369
+ with self._edit_lock:
370
+ return super().delete(table, where)
@@ -1,3 +1,4 @@
1
+ from . import _sql_base
1
2
  from ._sql_base import *
2
3
  from MainShortcuts2.ex import sqlite_ex
3
4
  from MainShortcuts2.ex.pathlib_ex import Path
@@ -112,3 +113,7 @@ class Database(SyncDatabaseBase):
112
113
 
113
114
  def _update(self, table: str, values: dict, where: dict):
114
115
  self.exec(*sqlite_ex.make_update_sql(table, values, where), fetch=False)
116
+
117
+ def select_count(self, table: TABLE_NAME, where: dict = None):
118
+ with self.cursor() as cur:
119
+ return cur.select_count(_sql_base._gtn(table), where)
@@ -1,4 +1,6 @@
1
1
  """Различные объекты и исключения"""
2
+ from collections import OrderedDict
3
+ import threading
2
4
  from typing import NamedTuple
3
5
 
4
6
 
@@ -470,6 +472,7 @@ class ThreadsFlag(BoolFlag):
470
472
 
471
473
 
472
474
  class BitsTuple(NamedTuple):
475
+ """1 байт в виде 8-ми битов"""
473
476
  b0: int
474
477
  b1: int
475
478
  b2: int
@@ -566,3 +569,44 @@ Error403 = AccessDeniedError
566
569
  Error404 = NotFoundError
567
570
  Inf = Infinity
568
571
  NaN = NotANumber
572
+
573
+
574
+ class LRUDict(OrderedDict):
575
+ """
576
+ :class:`OrderedDict` с ограничением по размеру.
577
+ При переполнении вытесняет старейшие элементы
578
+ """
579
+
580
+ def __init__(self, size: int):
581
+ super().__init__()
582
+ if size < 0:
583
+ raise ValueError("Negative size")
584
+ self._lock = threading.RLock()
585
+ self.limit = size
586
+
587
+ def __setitem__(self, key, value):
588
+ with self._lock:
589
+ if key in self:
590
+ self.move_to_end(key, last=True)
591
+ else:
592
+ super().__setitem__(key, value)
593
+ while len(self) > self.limit:
594
+ self.popitem(False)
595
+
596
+ def delete_old(self):
597
+ """Обрезать словарь до лимита"""
598
+ with self._lock:
599
+ while len(self) > self.limit:
600
+ self.popitem(False)
601
+
602
+
603
+ class LRUDictWithRefresh(LRUDict):
604
+ """
605
+ :class:`LRUDict`, который обновляет порядок элементов
606
+ не только при записи, но и при чтении
607
+ """
608
+
609
+ def __getitem__(self, key):
610
+ with self._lock:
611
+ self.move_to_end(key, last=False)
612
+ return super().__getitem__(key)
@@ -1,52 +0,0 @@
1
- [tool.poetry]
2
- version = "2.10.1"
3
- name = "MainShortcuts2"
4
- description = "Сокращение и улучшение функций + консольные утилиты"
5
- authors = ["MainPlay TG <xbox.roman6666666666@gmail.com>"]
6
- readme = "README.md"
7
- repository = "https://github.com/MainPlay-TG/MainShortcuts2.py"
8
- packages = [
9
- { include = "MainShortcuts2", from = "src" },
10
- ]
11
-
12
- [tool.poetry.scripts]
13
- micro-json = "MainShortcuts2.__main__:micro_json"
14
- ms2-app = "MainShortcuts2.ms2app:main"
15
- ms2-hash_check = "MainShortcuts2.ms2hash:hash_check"
16
- ms2-hash_gen = "MainShortcuts2.ms2hash:hash_gen"
17
- ms2-hash_java = "MainShortcuts2.ms2hash:run_java_ext"
18
- ms2-import_example = "MainShortcuts2.__main__:import_example"
19
- ms2-ln = "MainShortcuts2.__main__:ln"
20
- ms2-which_real = "MainShortcuts2.__main__:which_real"
21
- nano-json = "MainShortcuts2.__main__:nano_json"
22
- nginx-reload = "MainShortcuts2.__main__:nginx_reload"
23
- nginx-restart = "MainShortcuts2.__main__:nginx_restart"
24
- ms2java-launch = "MainShortcuts2.java_launch.__main__:launch"
25
- ms2java-info = "MainShortcuts2.java_launch.__main__:print_info"
26
-
27
- [tool.poetry.dependencies]
28
- python = "^3.10"
29
-
30
- # Любые синхронные функции с использованием HTTP
31
- requests = { version = "^2.32.5", optional = true }
32
-
33
- # ms2dat1crypto
34
- cryptography = { version = "^50.0.0", optional = true }
35
-
36
- # Все прочие необязательные зависимости
37
- aiohttp = { version = "^3.14.3", optional = true }
38
- colorama = { version = "^0.4.6", optional = true }
39
- json5 = { version = "^0.15.0", optional = true }
40
- pillow = { version = "^12.3.0", optional = true }
41
- progressbar2 = { version = "^4.6.0", optional = true }
42
- psutil = { version = "^7.2.2", optional = true }
43
- pyside6 = { version = "^6.11.2", optional = true }
44
-
45
- [tool.poetry.extras]
46
- crypto = ["cryptography"]
47
- full = ["aiohttp","colorama","cryptography","json5","pillow","progressbar2","psutil","pyside6","requests"]
48
- http = ["requests"]
49
-
50
- [build-system]
51
- build-backend = "poetry.core.masonry.api"
52
- requires = ["poetry-core"]