silentstudio 0.3.0__tar.gz → 0.3.2__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 (25) hide show
  1. {silentstudio-0.3.0/src/silentstudio.egg-info → silentstudio-0.3.2}/PKG-INFO +38 -1
  2. {silentstudio-0.3.0 → silentstudio-0.3.2}/README.md +37 -0
  3. {silentstudio-0.3.0 → silentstudio-0.3.2}/pyproject.toml +1 -1
  4. {silentstudio-0.3.0 → silentstudio-0.3.2}/setup.py +1 -1
  5. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/__init__.py +1 -1
  6. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/cli.py +29 -48
  7. silentstudio-0.3.2/src/silentstudio/config_cli.py +72 -0
  8. silentstudio-0.3.2/src/silentstudio/i18n.py +312 -0
  9. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/installer.py +68 -53
  10. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/release.py +32 -13
  11. silentstudio-0.3.2/src/silentstudio/sources.py +150 -0
  12. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/utils.py +42 -15
  13. {silentstudio-0.3.0 → silentstudio-0.3.2/src/silentstudio.egg-info}/PKG-INFO +38 -1
  14. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio.egg-info/SOURCES.txt +3 -0
  15. {silentstudio-0.3.0 → silentstudio-0.3.2}/LICENSE +0 -0
  16. {silentstudio-0.3.0 → silentstudio-0.3.2}/setup.cfg +0 -0
  17. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/__main__.py +0 -0
  18. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/config.py +0 -0
  19. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/list_packages.py +0 -0
  20. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/platform.py +0 -0
  21. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio/project_new.py +0 -0
  22. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio.egg-info/dependency_links.txt +0 -0
  23. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio.egg-info/entry_points.txt +0 -0
  24. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio.egg-info/requires.txt +0 -0
  25. {silentstudio-0.3.0 → silentstudio-0.3.2}/src/silentstudio.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: silentstudio
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: SilentStudio CLI - 让开发者体验更好一点
5
5
  Home-page: https://github.com/Silent-Studio-CN/SilentStudioCLI
6
6
  Author: SilentStudio
@@ -230,6 +230,14 @@ silentstudio requests
230
230
 
231
231
  ---
232
232
 
233
+ 也可以通过 `ss install <包名>` 安装;安装时会流式显示各源版本,并提示选择源:
234
+
235
+ ```bash
236
+ ss install pyqt6
237
+ ```
238
+
239
+ 支持输入编号(1-4)、源名称(如 tencent,忽略大小写),或直接回车自动选择最新源。
240
+
233
241
  ### 5. 列出已安装的库
234
242
 
235
243
  ```bash
@@ -258,8 +266,37 @@ ss install list
258
266
 
259
267
  ---
260
268
 
269
+ ### 6. 多源版本查询
270
+
271
+ ```bash
272
+ ss sources silentstudio
273
+ ```
274
+
275
+ 同时查询 PyPI、阿里云、清华、腾讯云等索引,显示每个源的最新版本:
276
+
277
+ ```text
278
+ Package: silentstudio
279
+ Source Version URL
280
+ ------------------------------------------------------------------------
281
+ PyPI 0.3.1 https://pypi.org/simple
282
+ Aliyun 0.1.7 https://mirrors.aliyun.com/pypi/simple
283
+ Tsinghua 0.1.7 https://pypi.tuna.tsinghua.edu.cn/simple
284
+ Tencent 0.1.7 https://mirrors.cloud.tencent.com/pypi/simple
285
+ ```
286
+
287
+ `ss install <包名>` 会先打印同样的源版本表,然后自动选择版本最新的源安装;如果失败,会按顺序回退到其他源。
288
+
289
+ ---
290
+
261
291
  ## 🔧 配置
262
292
 
293
+ ```bash
294
+ ss config # 查看全部配置
295
+ ss config install # 交互式修改安装范围
296
+ ss config language ja # 修改语言
297
+ ```
298
+
299
+
263
300
  SilentStudio 在用户目录下创建 `~/.silentstudio/` 文件夹:
264
301
 
265
302
  ```
@@ -210,6 +210,14 @@ silentstudio requests
210
210
 
211
211
  ---
212
212
 
213
+ 也可以通过 `ss install <包名>` 安装;安装时会流式显示各源版本,并提示选择源:
214
+
215
+ ```bash
216
+ ss install pyqt6
217
+ ```
218
+
219
+ 支持输入编号(1-4)、源名称(如 tencent,忽略大小写),或直接回车自动选择最新源。
220
+
213
221
  ### 5. 列出已安装的库
214
222
 
215
223
  ```bash
@@ -238,8 +246,37 @@ ss install list
238
246
 
239
247
  ---
240
248
 
249
+ ### 6. 多源版本查询
250
+
251
+ ```bash
252
+ ss sources silentstudio
253
+ ```
254
+
255
+ 同时查询 PyPI、阿里云、清华、腾讯云等索引,显示每个源的最新版本:
256
+
257
+ ```text
258
+ Package: silentstudio
259
+ Source Version URL
260
+ ------------------------------------------------------------------------
261
+ PyPI 0.3.1 https://pypi.org/simple
262
+ Aliyun 0.1.7 https://mirrors.aliyun.com/pypi/simple
263
+ Tsinghua 0.1.7 https://pypi.tuna.tsinghua.edu.cn/simple
264
+ Tencent 0.1.7 https://mirrors.cloud.tencent.com/pypi/simple
265
+ ```
266
+
267
+ `ss install <包名>` 会先打印同样的源版本表,然后自动选择版本最新的源安装;如果失败,会按顺序回退到其他源。
268
+
269
+ ---
270
+
241
271
  ## 🔧 配置
242
272
 
273
+ ```bash
274
+ ss config # 查看全部配置
275
+ ss config install # 交互式修改安装范围
276
+ ss config language ja # 修改语言
277
+ ```
278
+
279
+
243
280
  SilentStudio 在用户目录下创建 `~/.silentstudio/` 文件夹:
244
281
 
245
282
  ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "silentstudio"
7
- version = "0.3.0"
7
+ version = "0.3.2"
8
8
  description = "SilentStudio CLI - 让开发者体验更好一点"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -5,7 +5,7 @@ with open("README.md", "r", encoding="utf-8") as f:
5
5
 
6
6
  setup(
7
7
  name="silentstudio",
8
- version="0.3.0",
8
+ version="0.3.2",
9
9
  author="SilentStudio",
10
10
  author_email="SilentStudio@Home.email.cn",
11
11
  description="SilentStudio CLI - 让开发者体验更好一点",
@@ -1,3 +1,3 @@
1
- __version__ = "0.3.0"
1
+ __version__ = "0.3.2"
2
2
  __author__ = "SilentStudio"
3
3
  __description__ = "SilentStudio CLI - 让开发者体验更好一点"
@@ -10,57 +10,14 @@ from .utils import get_system_language
10
10
  from .installer import handle_install
11
11
  from .list_packages import handle_list_packages
12
12
  from .project_new import handle_new
13
+ from .sources import handle_sources
13
14
  from .platform import ensure_command_aliases
14
15
 
15
16
 
16
17
  def show_help(lang: str) -> None:
17
18
  """显示帮助信息"""
18
- if lang == "zh-CN":
19
- print(f"""
20
- SilentStudio CLI v{__version__} - 让开发者体验更好一点
21
- 主页: https://github.com/Silent-Studio-CN/SilentStudioCLI
22
-
23
- 用法:
24
- silentstudio 显示此帮助信息
25
- silentstudio -v, --version 显示版本号
26
- silentstudio new <name> -l <lang> 创建新项目
27
- silentstudio new <name> --lang <lang>创建新项目
28
- silentstudio <pkg_name> 查询并安装生态库
29
- silentstudio install list 列出已安装的库
30
- silentstudio release <project> <ver> 触发 GitHub Release
31
- silentstudio git <args...> git 透传
32
- silentstudio status / commit / push 常用 git 快捷命令
33
-
34
- 示例:
35
- silentstudio new my-app -l java
36
- silentstudio slimemold
37
- silentstudio install list
38
-
39
- 更多信息: https://github.com/Silent-Studio-CN/SilentStudioCLI
40
- """)
41
- else:
42
- print(f"""
43
- SilentStudio CLI v{__version__} - Making developer experience better
44
- Home: https://github.com/Silent-Studio-CN/SilentStudioCLI
45
-
46
- Usage:
47
- silentstudio Show this help
48
- silentstudio -v, --version Show version
49
- silentstudio new <name> -l <lang> Create new project
50
- silentstudio new <name> --lang <lang> Create new project
51
- silentstudio <pkg_name> Query and install package
52
- silentstudio install list List installed packages
53
- silentstudio release <project> <ver> Trigger a GitHub release
54
- silentstudio git <args...> Pass through to git
55
- silentstudio status / commit / push Common git shortcuts
56
-
57
- Examples:
58
- silentstudio new my-app -l java
59
- silentstudio slimemold
60
- silentstudio install list
61
-
62
- More info: https://github.com/Silent-Studio-CN/SilentStudioCLI
63
- """)
19
+ from .i18n import help_text
20
+ print(help_text(__version__, lang))
64
21
 
65
22
 
66
23
  GIT_COMMANDS = {
@@ -69,10 +26,11 @@ GIT_COMMANDS = {
69
26
  }
70
27
 
71
28
 
72
- def main():
29
+ def _main():
73
30
  """主入口"""
74
31
  ensure_command_aliases()
75
- lang = get_system_language()
32
+ config = load_config()
33
+ lang = get_system_language(config.get("language", "auto"))
76
34
 
77
35
  argv = sys.argv[1:]
78
36
  if argv and argv[0] in ("release", "releases"):
@@ -82,6 +40,14 @@ def main():
82
40
  return subprocess.call(["git", *argv[1:]])
83
41
  if argv and argv[0] in GIT_COMMANDS:
84
42
  return subprocess.call(["git", *argv])
43
+ if argv and argv[0] == "install" and len(argv) > 1 and argv[1] != "list":
44
+ return handle_install(argv[1], lang)
45
+ if argv and argv[0] == "config":
46
+ from .config_cli import handle_config
47
+ return handle_config(argv[1:])
48
+ if argv and argv[0].startswith("-") and argv[0] not in ("-v", "--version", "-h", "--help"):
49
+ print("Unknown option: " + argv[0])
50
+ return 2
85
51
 
86
52
  # 检查是否有参数
87
53
  if len(sys.argv) == 1:
@@ -111,6 +77,9 @@ def main():
111
77
  install_parser = subparsers.add_parser("install", help="安装相关", add_help=False)
112
78
  install_subparsers = install_parser.add_subparsers(dest="install_cmd", help="安装子命令")
113
79
  list_parser = install_subparsers.add_parser("list", help="列出已安装的库", add_help=False)
80
+
81
+ sources_parser = subparsers.add_parser("sources", help="查看各 PyPI 源的版本", add_help=False)
82
+ sources_parser.add_argument("package", help="包名")
114
83
 
115
84
  # 解析已知参数,忽略未知(处理 silentstudio <pkg_name>)
116
85
  args, unknown = parser.parse_known_args()
@@ -130,6 +99,9 @@ def main():
130
99
  if args.command == "new":
131
100
  return handle_new(args.name, args.language)
132
101
 
102
+ if args.command == "sources":
103
+ return handle_sources(args.package)
104
+
133
105
  if args.command == "install":
134
106
  if args.install_cmd == "list":
135
107
  return handle_list_packages()
@@ -152,5 +124,14 @@ def main():
152
124
  return 0
153
125
 
154
126
 
127
+ def main():
128
+ try:
129
+ return _main()
130
+ except KeyboardInterrupt:
131
+ from .i18n import tr
132
+ print("\n" + tr("cancelled", get_system_language()))
133
+ return 130
134
+
135
+
155
136
  if __name__ == "__main__":
156
137
  sys.exit(main())
@@ -0,0 +1,72 @@
1
+ """ss config command."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+
6
+ from .config import load_config, save_config
7
+ from .i18n import LANGUAGES, normalize_language
8
+ from .utils import get_system_language
9
+
10
+ KEYS = {
11
+ "language": "auto | " + " | ".join(LANGUAGES),
12
+ "install_scope": "user | system",
13
+ "pypi_mirror": "PyPI mirror URL",
14
+ "index_url": "SilentStudio index URL",
15
+ }
16
+
17
+
18
+ def _current(lang: str, scope: str) -> str:
19
+ return f"当前安装范围: {scope}" if lang == "zh-CN" else f"Current install scope: {scope}"
20
+
21
+
22
+ def handle_config(argv: list[str]) -> int:
23
+ config = load_config()
24
+ lang = get_system_language(config.get("language", "auto"))
25
+
26
+ if not argv:
27
+ for key, desc in KEYS.items():
28
+ print(f"{key} = {config.get(key, '')} # {desc}")
29
+ return 0
30
+
31
+ key = argv[0].lower()
32
+ if key == "install":
33
+ key = "install_scope"
34
+
35
+ if key not in KEYS:
36
+ print(f"Unknown config key: {key}" if lang != "zh-CN" else f"未知配置项:{key}")
37
+ print("Keys: " + ", ".join(KEYS))
38
+ return 2
39
+
40
+ value = argv[1] if len(argv) > 1 else None
41
+
42
+ if key == "install_scope":
43
+ if value is None:
44
+ print(_current(lang, config.get("install_scope", "user")))
45
+ prompt = "选择安装范围 [1] user [2] system: " if lang == "zh-CN" else "Install scope [1] user [2] system: "
46
+ try:
47
+ choice = input(prompt).strip()
48
+ except (EOFError, KeyboardInterrupt):
49
+ print()
50
+ return 130
51
+ value = {"1": "user", "2": "system"}.get(choice, choice)
52
+ value = value.lower()
53
+ if value not in ("user", "system"):
54
+ print("install_scope must be user or system")
55
+ return 2
56
+
57
+ if key == "language":
58
+ if value is None:
59
+ print(f"language = {config.get('language', 'auto')}")
60
+ prompt = "选择语言(auto/en/zh-CN/zh-TW/ja/ko/ru/es/it): "
61
+ try:
62
+ value = input(prompt).strip()
63
+ except (EOFError, KeyboardInterrupt):
64
+ print()
65
+ return 130
66
+ if value != "auto":
67
+ value = normalize_language(value)
68
+
69
+ config[key] = value
70
+ save_config(config)
71
+ print(f"{key} = {value}")
72
+ return 0
@@ -0,0 +1,312 @@
1
+ """Small built-in localization layer for the CLI."""
2
+ from __future__ import annotations
3
+
4
+ import locale
5
+ import os
6
+ from typing import Dict
7
+
8
+ LANGUAGES: Dict[str, str] = {
9
+ "en": "English",
10
+ "zh-CN": "简体中文",
11
+ "zh-TW": "繁體中文",
12
+ "ja": "日本語",
13
+ "ko": "한국어",
14
+ "ru": "Русский",
15
+ "es": "Español",
16
+ "it": "Italiano",
17
+ }
18
+
19
+ STRINGS: Dict[str, Dict[str, str]] = {
20
+ "en": {
21
+ "cancelled": "Cancelled.",
22
+ "project": "Project name",
23
+ "repository": "Repository",
24
+ "workflow": "Workflow",
25
+ "ref": "Ref",
26
+ "tag": "Tag template",
27
+ "saved": "Saved {project} to {path}",
28
+ "invalid_repo": "Invalid repository: {repo!r}. Expected owner/repo",
29
+ "configured": "Configured projects:",
30
+ "usage": "Usage: ss release <project> <version> [commit]",
31
+ "no_projects": "No projects configured. Run: ss release config",
32
+ "version_required": "version is required",
33
+ "unknown_project": "Project '{project}' is not configured. Run: ss release config {project}",
34
+ "package": "Package",
35
+ "source": "Source",
36
+ "version": "Version",
37
+ "not_found": "not found",
38
+ },
39
+ "zh-CN": {
40
+ "cancelled": "已取消。",
41
+ "project": "项目名称",
42
+ "repository": "仓库",
43
+ "workflow": "工作流",
44
+ "ref": "引用",
45
+ "tag": "Tag 模板",
46
+ "saved": "已保存 {project} 到 {path}",
47
+ "invalid_repo": "仓库格式无效:{repo!r},应为 owner/repo",
48
+ "configured": "已配置项目:",
49
+ "usage": "用法:ss release <project> <version> [commit]",
50
+ "no_projects": "还没有配置项目。运行:ss release config",
51
+ "version_required": "缺少版本号",
52
+ "unknown_project": "项目 '{project}' 未配置。运行:ss release config {project}",
53
+ "package": "包名",
54
+ "source": "源",
55
+ "version": "版本",
56
+ "not_found": "未找到",
57
+ },
58
+ "zh-TW": {
59
+ "cancelled": "已取消。",
60
+ "project": "專案名稱",
61
+ "repository": "倉庫",
62
+ "workflow": "工作流程",
63
+ "ref": "參照",
64
+ "tag": "Tag 範本",
65
+ "saved": "已儲存 {project} 到 {path}",
66
+ "invalid_repo": "倉庫格式無效:{repo!r},應為 owner/repo",
67
+ "configured": "已設定專案:",
68
+ "usage": "用法:ss release <project> <version> [commit]",
69
+ "no_projects": "尚未設定專案。執行:ss release config",
70
+ "version_required": "缺少版本號",
71
+ "unknown_project": "專案 '{project}' 未設定。執行:ss release config {project}",
72
+ "package": "套件",
73
+ "source": "來源",
74
+ "version": "版本",
75
+ "not_found": "找不到",
76
+ },
77
+ "ja": {
78
+ "cancelled": "キャンセルしました。",
79
+ "project": "プロジェクト名",
80
+ "repository": "リポジトリ",
81
+ "workflow": "ワークフロー",
82
+ "ref": "参照",
83
+ "tag": "タグのテンプレート",
84
+ "saved": "{project} を {path} に保存しました",
85
+ "invalid_repo": "リポジトリ形式が無効です: {repo!r}(owner/repo)",
86
+ "configured": "設定済みプロジェクト:",
87
+ "usage": "使い方: ss release <project> <version> [commit]",
88
+ "no_projects": "プロジェクトが未設定です。実行: ss release config",
89
+ "version_required": "バージョンが必要です",
90
+ "unknown_project": "プロジェクト '{project}' は未設定です。実行: ss release config {project}",
91
+ "package": "パッケージ",
92
+ "source": "ソース",
93
+ "version": "バージョン",
94
+ "not_found": "見つかりません",
95
+ },
96
+ "ko": {
97
+ "cancelled": "취소되었습니다.",
98
+ "project": "프로젝트 이름",
99
+ "repository": "저장소",
100
+ "workflow": "워크플로",
101
+ "ref": "참조",
102
+ "tag": "태그 템플릿",
103
+ "saved": "{project}을(를) {path}에 저장했습니다",
104
+ "invalid_repo": "저장소 형식이 잘못되었습니다: {repo!r} (owner/repo)",
105
+ "configured": "설정된 프로젝트:",
106
+ "usage": "사용법: ss release <project> <version> [commit]",
107
+ "no_projects": "설정된 프로젝트가 없습니다. 실행: ss release config",
108
+ "version_required": "버전이 필요합니다",
109
+ "unknown_project": "프로젝트 '{project}'이(가) 설정되지 않았습니다. 실행: ss release config {project}",
110
+ "package": "패키지",
111
+ "source": "소스",
112
+ "version": "버전",
113
+ "not_found": "찾을 수 없음",
114
+ },
115
+ "ru": {
116
+ "cancelled": "Отменено.",
117
+ "project": "Имя проекта",
118
+ "repository": "Репозиторий",
119
+ "workflow": "Workflow",
120
+ "ref": "Ветка/ref",
121
+ "tag": "Шаблон тега",
122
+ "saved": "Сохранено {project} в {path}",
123
+ "invalid_repo": "Неверный формат репозитория: {repo!r}. Нужно owner/repo",
124
+ "configured": "Настроенные проекты:",
125
+ "usage": "Использование: ss release <project> <version> [commit]",
126
+ "no_projects": "Проекты не настроены. Запустите: ss release config",
127
+ "version_required": "Требуется версия",
128
+ "unknown_project": "Проект '{project}' не настроен. Запустите: ss release config {project}",
129
+ "package": "Пакет",
130
+ "source": "Источник",
131
+ "version": "Версия",
132
+ "not_found": "не найдено",
133
+ },
134
+ "es": {
135
+ "cancelled": "Cancelado.",
136
+ "project": "Nombre del proyecto",
137
+ "repository": "Repositorio",
138
+ "workflow": "Workflow",
139
+ "ref": "Referencia",
140
+ "tag": "Plantilla de tag",
141
+ "saved": "Guardado {project} en {path}",
142
+ "invalid_repo": "Repositorio inválido: {repo!r}. Se espera owner/repo",
143
+ "configured": "Proyectos configurados:",
144
+ "usage": "Uso: ss release <project> <version> [commit]",
145
+ "no_projects": "No hay proyectos configurados. Ejecuta: ss release config",
146
+ "version_required": "Falta la versión",
147
+ "unknown_project": "El proyecto '{project}' no está configurado. Ejecuta: ss release config {project}",
148
+ "package": "Paquete",
149
+ "source": "Fuente",
150
+ "version": "Versión",
151
+ "not_found": "no encontrado",
152
+ },
153
+ "it": {
154
+ "cancelled": "Annullato.",
155
+ "project": "Nome progetto",
156
+ "repository": "Repository",
157
+ "workflow": "Workflow",
158
+ "ref": "Riferimento",
159
+ "tag": "Template tag",
160
+ "saved": "Salvato {project} in {path}",
161
+ "invalid_repo": "Repository non valido: {repo!r}. Atteso owner/repo",
162
+ "configured": "Progetti configurati:",
163
+ "usage": "Uso: ss release <project> <version> [commit]",
164
+ "no_projects": "Nessun progetto configurato. Esegui: ss release config",
165
+ "version_required": "Versione richiesta",
166
+ "unknown_project": "Il progetto '{project}' non è configurato. Esegui: ss release config {project}",
167
+ "package": "Pacchetto",
168
+ "source": "Fonte",
169
+ "version": "Versione",
170
+ "not_found": "non trovato",
171
+ },
172
+ }
173
+
174
+
175
+ def normalize_language(value: str) -> str:
176
+ value = (value or "").replace("_", "-").lower()
177
+ if value.startswith("zh"):
178
+ if any(tag in value for tag in ("tw", "hk", "mo", "hant")):
179
+ return "zh-TW"
180
+ return "zh-CN"
181
+ for code in LANGUAGES:
182
+ if value == code.lower() or value.startswith(code.lower() + "-"):
183
+ return code
184
+ return "en"
185
+
186
+
187
+ def detect_language() -> str:
188
+ raw = (os.environ.get("LC_ALL") or os.environ.get("LC_MESSAGES")
189
+ or os.environ.get("LANG") or "")
190
+ if raw:
191
+ return normalize_language(raw)
192
+ try:
193
+ value = locale.getdefaultlocale()[0]
194
+ if value:
195
+ return normalize_language(value)
196
+ except Exception:
197
+ pass
198
+ return "en"
199
+
200
+
201
+ def get_language(config_lang: str = "auto") -> str:
202
+ if config_lang and config_lang != "auto":
203
+ return normalize_language(config_lang)
204
+ return detect_language()
205
+
206
+
207
+ def tr(key: str, lang: str = "en", **kwargs) -> str:
208
+ table = STRINGS.get(lang, STRINGS["en"])
209
+ text = table.get(key, STRINGS["en"].get(key, key))
210
+ try:
211
+ return text.format(**kwargs)
212
+ except Exception:
213
+ return text
214
+
215
+
216
+ HELP_TEXT = {
217
+ "en": {
218
+ "usage": "Usage", "examples": "Examples", "more": "More info",
219
+ "show_help": "Show this help", "show_version": "Show version",
220
+ "new": "Create a new project", "pkg": "Install an ecosystem package",
221
+ "install_list": "List installed packages", "sources": "Show versions across PyPI sources",
222
+ "release": "Publish a GitHub release", "git": "Pass through to git",
223
+ "shortcuts": "Common git shortcuts",
224
+ },
225
+ "zh-CN": {
226
+ "usage": "用法", "examples": "示例", "more": "更多信息",
227
+ "show_help": "显示此帮助", "show_version": "显示版本号",
228
+ "new": "创建新项目", "pkg": "查询并安装生态库",
229
+ "install_list": "列出已安装的库", "sources": "查看各 PyPI 源的版本",
230
+ "release": "触发 GitHub Release", "git": "git 透传",
231
+ "shortcuts": "常用 git 快捷命令",
232
+ },
233
+ "zh-TW": {
234
+ "usage": "用法", "examples": "範例", "more": "更多資訊",
235
+ "show_help": "顯示此說明", "show_version": "顯示版本號",
236
+ "new": "建立新專案", "pkg": "查詢並安裝生態套件",
237
+ "install_list": "列出已安裝的套件", "sources": "查看各 PyPI 來源的版本",
238
+ "release": "觸發 GitHub Release", "git": "git 透傳",
239
+ "shortcuts": "常用 git 快捷指令",
240
+ },
241
+ "ja": {
242
+ "usage": "使い方", "examples": "例", "more": "詳細",
243
+ "show_help": "このヘルプを表示", "show_version": "バージョンを表示",
244
+ "new": "新しいプロジェクトを作成", "pkg": "エコシステムのパッケージをインストール",
245
+ "install_list": "インストール済みパッケージを一覧", "sources": "PyPI ソースごとのバージョンを表示",
246
+ "release": "GitHub Release を実行", "git": "git にそのまま渡す",
247
+ "shortcuts": "よく使う git コマンド",
248
+ },
249
+ "ko": {
250
+ "usage": "사용법", "examples": "예시", "more": "자세히",
251
+ "show_help": "도움말 표시", "show_version": "버전 표시",
252
+ "new": "새 프로젝트 만들기", "pkg": "생태계 패키지 설치",
253
+ "install_list": "설치된 패키지 목록", "sources": "PyPI 소스별 버전 표시",
254
+ "release": "GitHub Release 실행", "git": "git으로 전달",
255
+ "shortcuts": "자주 쓰는 git 명령",
256
+ },
257
+ "ru": {
258
+ "usage": "Использование", "examples": "Примеры", "more": "Подробнее",
259
+ "show_help": "Показать справку", "show_version": "Показать версию",
260
+ "new": "Создать новый проект", "pkg": "Установить пакет экосистемы",
261
+ "install_list": "Список установленных пакетов", "sources": "Версии по источникам PyPI",
262
+ "release": "Запустить GitHub Release", "git": "Передать в git",
263
+ "shortcuts": "Частые команды git",
264
+ },
265
+ "es": {
266
+ "usage": "Uso", "examples": "Ejemplos", "more": "Más información",
267
+ "show_help": "Mostrar esta ayuda", "show_version": "Mostrar versión",
268
+ "new": "Crear un proyecto nuevo", "pkg": "Instalar un paquete del ecosistema",
269
+ "install_list": "Listar paquetes instalados", "sources": "Mostrar versiones por fuente PyPI",
270
+ "release": "Publicar un GitHub Release", "git": "Pasar directamente a git",
271
+ "shortcuts": "Atajos de git habituales",
272
+ },
273
+ "it": {
274
+ "usage": "Uso", "examples": "Esempi", "more": "Ulteriori informazioni",
275
+ "show_help": "Mostra questo aiuto", "show_version": "Mostra versione",
276
+ "new": "Crea un nuovo progetto", "pkg": "Installa un pacchetto dell'ecosistema",
277
+ "install_list": "Elenca i pacchetti installati", "sources": "Mostra le versioni per fonte PyPI",
278
+ "release": "Pubblica una GitHub Release", "git": "Passa direttamente a git",
279
+ "shortcuts": "Scorciatoie git comuni",
280
+ },
281
+ }
282
+
283
+
284
+ def help_text(version: str, lang: str) -> str:
285
+ h = HELP_TEXT.get(lang, HELP_TEXT["en"])
286
+ lines = [
287
+ f"SilentStudio CLI v{version}",
288
+ "Home: https://github.com/Silent-Studio-CN/SilentStudioCLI",
289
+ "",
290
+ f"{h['usage']}:",
291
+ f" ss {h['show_help']}",
292
+ f" ss -v, --version {h['show_version']}",
293
+ f" ss new <name> -l <lang> {h['new']}",
294
+ f" ss <pkg> {h['pkg']}",
295
+ f" ss install list {h['install_list']}",
296
+ f" ss sources <pkg> {h['sources']}",
297
+ f" ss config [key] [value] {h.get('config', 'Show or change configuration')}",
298
+ f" ss release <project> <version> {h['release']}",
299
+ f" ss git <args...> {h['git']}",
300
+ f" ss status/commit/push {h['shortcuts']}",
301
+ "",
302
+ f"{h['examples']}:",
303
+ " ss new my-app -l java",
304
+ " ss slimemold",
305
+ " ss install list",
306
+ " ss sources silentstudio",
307
+ " ss release silentcraft 3.18",
308
+ "",
309
+ f"{h['more']}: https://github.com/Silent-Studio-CN/SilentStudioCLI",
310
+ ]
311
+ return "\n".join(lines)
312
+
@@ -5,11 +5,13 @@ from typing import Optional, Dict, Any, Tuple
5
5
  import requests
6
6
 
7
7
  from .config import load_config, load_installed, save_installed
8
+ from .sources import _version_key
8
9
  from .utils import (
9
10
  get_system_language,
10
11
  run_pip_command,
11
12
  check_package_installed,
12
13
  get_package_version,
14
+ spinner as animate_spinner,
13
15
  )
14
16
 
15
17
 
@@ -49,27 +51,64 @@ def check_pypi(pkg_name: str) -> Tuple[bool, Optional[str]]:
49
51
  return False, None
50
52
 
51
53
 
52
- def install_package(pkg_name: str, channel: str = "pypi") -> Tuple[bool, str]:
53
- """安装包"""
54
+ def _choose_source(rows, lang: str):
55
+ if not sys.stdin.isatty():
56
+ best = max(rows, key=lambda item: _version_key(item[2])) if any(r[2] for r in rows) else rows[0]
57
+ return best
58
+
59
+ while True:
60
+ prompt = "选择安装源(编号/名称,回车自动): " if lang == "zh-CN" else "Select source (number/name, Enter auto): "
61
+ try:
62
+ choice = input(prompt).strip()
63
+ except EOFError:
64
+ print()
65
+ return max(rows, key=lambda item: _version_key(item[2])) if any(r[2] for r in rows) else rows[0]
66
+ if not choice:
67
+ return max(rows, key=lambda item: _version_key(item[2])) if any(r[2] for r in rows) else rows[0]
68
+ if choice.isdigit():
69
+ index = int(choice)
70
+ if 1 <= index <= len(rows):
71
+ return rows[index - 1]
72
+ for row in rows:
73
+ if row[0].lower() == choice.lower():
74
+ return row
75
+ print("无效的源,请重新输入。" if lang == "zh-CN" else "Invalid source, try again.")
76
+
77
+
78
+ def install_package(pkg_name: str, channel: str = "pypi", source=None) -> Tuple[bool, str]:
79
+ """安装包;source 为空时查询所有源并交互选择。"""
54
80
  config = load_config()
55
81
  scope = config.get("install_scope", "user")
56
-
57
- if channel == "pypi":
58
- success, stdout, stderr = run_pip_command(
59
- ["install", pkg_name],
60
- scope=scope
61
- )
62
- if success:
63
- # 记录安装
64
- version = get_package_version(pkg_name)
65
- if version:
66
- record_installation(pkg_name, version, "pypi")
67
- return True, f"✅ 成功安装 {pkg_name} (版本: {version or '未知'})"
68
- else:
69
- return False, f"❌ 安装失败: {stderr or stdout}"
70
-
71
- return False, f"❌ 不支持的渠道: {channel}"
72
82
 
83
+ if channel != "pypi":
84
+ return False, f"❌ 不支持的渠道: {channel}"
85
+
86
+ from .sources import query_all, print_report, get_sources, _version_key
87
+
88
+ if source is None:
89
+ rows = query_all(pkg_name, spinner=True)
90
+ if not sys.stdout.isatty():
91
+ print_report(pkg_name, rows, show_package=False)
92
+ if not rows:
93
+ return False, f"❌ 未找到 {pkg_name} 的任何源"
94
+ source = _choose_source(rows, get_system_language())
95
+
96
+ name, url, version = source
97
+ if not version:
98
+ print(f"{name} 并没有查询到 {pkg_name},将尝试执行安装命令 1/1" if get_system_language() == "zh-CN"
99
+ else f"{name} did not report {pkg_name}; trying install anyway (1/1)")
100
+
101
+ success, stdout, stderr = run_pip_command(
102
+ ["install", "--upgrade", "-i", url, pkg_name],
103
+ scope=scope,
104
+ )
105
+ if success:
106
+ installed = get_package_version(pkg_name)
107
+ if installed:
108
+ record_installation(pkg_name, installed, "pypi")
109
+ return True, f"✅ 成功安装 {pkg_name} (版本: {installed or version or '未知'}, 源: {name})"
110
+
111
+ return False, f"❌ 安装失败: {stderr or stdout}"
73
112
 
74
113
  def record_installation(name: str, version: str, channel: str) -> None:
75
114
  """记录安装到 installed.json"""
@@ -105,8 +144,9 @@ def handle_install(pkg_name: str, lang: str) -> int:
105
144
  return 0
106
145
 
107
146
  # 1. 拉取 SilentStudio 索引
108
- print("📡 正在查询 SilentStudio 索引..." if lang == "zh-CN" else "📡 Querying SilentStudio index...")
109
- index = fetch_index()
147
+ label = "正在查询 SilentStudio 索引..." if lang == "zh-CN" else "Querying SilentStudio index..."
148
+ with animate_spinner(label):
149
+ index = fetch_index()
110
150
 
111
151
  # 查找匹配
112
152
  matched = None
@@ -129,36 +169,11 @@ def handle_install(pkg_name: str, lang: str) -> int:
129
169
  print(msg)
130
170
  return 0 if success else 1
131
171
 
132
- # 2. 未在索引中找到,回退到 PyPI
133
- msg_zh_not_found = f"⚠️ 您搜索的 '{pkg_name}' 并未在 SilentStudio 项目列表中查询到"
134
- msg_en_not_found = f"⚠️ '{pkg_name}' was not found in the SilentStudio project list"
135
- print(msg_zh_not_found if lang == "zh-CN" else msg_en_not_found)
136
-
137
- exists, version = check_pypi(pkg_name)
138
- if exists:
139
- msg_zh_pypi = f"📦 但在官方 PyPI 上找到了同名库 (最新版本: {version})"
140
- msg_en_pypi = f"📦 But found the same-named package on PyPI (latest version: {version})"
141
- print(msg_zh_pypi if lang == "zh-CN" else msg_en_pypi)
142
-
143
- prompt_zh = "是否安装?[y/N]: "
144
- prompt_en = "Install? [y/N]: "
145
- prompt = prompt_zh if lang == "zh-CN" else prompt_en
146
-
147
- try:
148
- answer = input(prompt).strip().lower()
149
- except KeyboardInterrupt:
150
- print("\n❌ 已取消")
151
- return 1
152
-
153
- if answer in ("y", "yes", "是"):
154
- success, msg = install_package(pkg_name, "pypi")
155
- print(msg)
156
- return 0 if success else 1
157
- else:
158
- print("❌ 已取消安装" if lang == "zh-CN" else "❌ Installation cancelled")
159
- return 0
160
- else:
161
- msg_zh_not_found_all = f"❌ 未在任何源中找到 '{pkg_name}'"
162
- msg_en_not_found_all = f"❌ '{pkg_name}' not found in any source"
163
- print(msg_zh_not_found_all if lang == "zh-CN" else msg_en_not_found_all)
164
- return 1
172
+ if not matched:
173
+ print(f"[{pkg_name}] 未在已配置的所有源列表中找到" if lang == "zh-CN"
174
+ else f"[{pkg_name}] was not found in any configured source")
175
+
176
+ target = matched.get("pkg_name", pkg_name) if matched else pkg_name
177
+ success, msg = install_package(target, "pypi")
178
+ print(msg)
179
+ return 0 if success else 1
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
 
4
4
  import argparse
5
5
  import json
6
+ import re
6
7
  import shutil
7
8
  import subprocess
8
9
  import sys
@@ -10,6 +11,9 @@ import time
10
11
  from pathlib import Path
11
12
  from typing import Any, Dict, Optional
12
13
 
14
+ from .i18n import tr
15
+ from .utils import get_system_language
16
+
13
17
  CONFIG_NAME = ".ss.json"
14
18
  USER_CONFIG = Path.home() / ".silentstudio" / "releases.json"
15
19
 
@@ -54,6 +58,7 @@ def save_project(project: str, data: Dict[str, Any]) -> Path:
54
58
  except Exception:
55
59
  config = {}
56
60
  config.setdefault("projects", {})[project] = data
61
+ config["defaultProject"] = project
57
62
  config_path.write_text(json.dumps(config, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
58
63
  return config_path
59
64
 
@@ -93,35 +98,49 @@ def handle_release(argv: list[str]) -> int:
93
98
  parser.add_argument("--config", action="store_true", help="configure a project")
94
99
  parser.add_argument("--list", action="store_true", help="list configured projects")
95
100
  args = parser.parse_args(argv)
96
-
101
+ if args.project == "config" and not args.version:
102
+ args.config = True
103
+ args.project = None
104
+ lang = get_system_language()
97
105
  projects = load_projects()
98
106
 
99
107
  if args.list:
100
108
  if not projects:
101
- print("No projects configured.")
109
+ print(tr("no_projects", lang))
102
110
  for name, data in projects.items():
103
111
  print(f"{name}\t{data.get('repo')}\t{data.get('workflow')}")
104
112
  return 0
105
113
 
106
- if args.config or not args.project:
107
- project = args.project or input("Project name [silentcraft]: ").strip() or "silentcraft"
114
+ if args.config:
115
+ project = args.project or input(f"{tr('project', lang)} [silentcraft]: ").strip() or "silentcraft"
108
116
  defaults = projects.get(project, DEFAULT_PROJECT)
109
- repo = input(f"Repository [{defaults.get('repo')}]: ").strip() or defaults.get("repo")
110
- workflow = input(f"Workflow [{defaults.get('workflow')}]: ").strip() or defaults.get("workflow")
111
- ref = input(f"Ref [{defaults.get('ref')}]: ").strip() or defaults.get("ref")
112
- tag = input(f"Tag template [{defaults.get('tag')}]: ").strip() or defaults.get("tag")
117
+ repo = input(f"{tr('repository', lang)} [{defaults.get('repo')}]: ").strip() or defaults.get("repo")
118
+ if not re.fullmatch(r"[^/\s]+/[^/\s]+", repo):
119
+ print(tr("invalid_repo", lang, repo=repo))
120
+ return 1
121
+ workflow = input(f"{tr('workflow', lang)} [{defaults.get('workflow')}]: ").strip() or defaults.get("workflow")
122
+ ref = input(f"{tr('ref', lang)} [{defaults.get('ref')}]: ").strip() or defaults.get("ref")
123
+ tag = input(f"{tr('tag', lang)} [{defaults.get('tag')}]: ").strip() or defaults.get("tag")
113
124
  path = save_project(project, {"repo": repo, "workflow": workflow, "ref": ref, "tag": tag})
114
- print(f"Saved {project} to {path}")
125
+ print(tr("saved", lang, project=project, path=path))
126
+ return 0
127
+
128
+ if not args.project:
129
+ if projects:
130
+ print(tr("configured", lang))
131
+ for name, data in projects.items():
132
+ print(f" {name}\t{data.get('repo')}")
133
+ print("\n" + tr("usage", lang))
134
+ else:
135
+ print(tr("no_projects", lang))
115
136
  return 0
116
137
 
117
138
  if not args.version:
118
- parser.error("version is required")
139
+ parser.error(tr("version_required", lang))
119
140
 
120
141
  data = projects.get(args.project)
121
142
  if not data:
122
- raise SystemExit(
123
- f"Project '{args.project}' is not configured. Run: ss release config {args.project}"
124
- )
143
+ raise SystemExit(tr("unknown_project", lang, project=args.project))
125
144
 
126
145
  repo = data["repo"]
127
146
  workflow = data["workflow"]
@@ -0,0 +1,150 @@
1
+ """Multi-index PyPI version discovery."""
2
+ from __future__ import annotations
3
+
4
+ import itertools
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ import threading
9
+ import time
10
+ from typing import Dict, List, Optional, Tuple
11
+
12
+ from .config import load_config
13
+ from .utils import spinner as animate_spinner
14
+
15
+ DEFAULT_SOURCES: List[Tuple[str, str]] = [
16
+ ("PyPI", "https://pypi.org/simple"),
17
+ ("Aliyun", "https://mirrors.aliyun.com/pypi/simple"),
18
+ ("Tsinghua", "https://pypi.tuna.tsinghua.edu.cn/simple"),
19
+ ("Tencent", "https://mirrors.cloud.tencent.com/pypi/simple"),
20
+ ]
21
+
22
+
23
+ def get_sources() -> List[Tuple[str, str]]:
24
+ config = load_config()
25
+ raw = config.get("pypi_sources")
26
+ if isinstance(raw, list) and raw:
27
+ result = []
28
+ for item in raw:
29
+ if isinstance(item, dict) and item.get("name") and item.get("url"):
30
+ result.append((item["name"], item["url"]))
31
+ elif isinstance(item, (list, tuple)) and len(item) == 2:
32
+ result.append((str(item[0]), str(item[1])))
33
+ if result:
34
+ return result
35
+ return list(DEFAULT_SOURCES)
36
+
37
+
38
+ def _parse_versions(output: str) -> List[str]:
39
+ match = re.search(r"Available versions:\s*(.+)", output)
40
+ if match:
41
+ return [v.strip() for v in match.group(1).split(",") if v.strip()]
42
+ match = re.search(r"^\S+\s+\(([^)]+)\)", output, re.MULTILINE)
43
+ return [match.group(1).strip()] if match else []
44
+
45
+
46
+ def query_source(package: str, url: str, timeout: int = 30) -> Optional[str]:
47
+ """Return the newest version advertised by one index, or None."""
48
+ try:
49
+ result = subprocess.run(
50
+ [sys.executable, "-m", "pip", "index", "versions", package,
51
+ "-i", url, "--disable-pip-version-check"],
52
+ capture_output=True, text=True, timeout=timeout,
53
+ )
54
+ versions = _parse_versions(result.stdout or result.stderr or "")
55
+ return versions[0] if versions else None
56
+ except Exception:
57
+ return None
58
+
59
+
60
+ def _stream_table(package: str, sources, minimum: float = 1.5):
61
+ """Query all sources concurrently and animate each version cell."""
62
+ rows = [None] * len(sources)
63
+
64
+ def worker(index: int, url: str) -> None:
65
+ rows[index] = query_source(package, url)
66
+
67
+ threads = []
68
+ for index, (_, url) in enumerate(sources):
69
+ thread = threading.Thread(target=worker, args=(index, url), daemon=True)
70
+ thread.start()
71
+ threads.append(thread)
72
+
73
+ print(f"Package: {package}")
74
+ print(f"{'Source':<12} {'Version':<16} URL")
75
+ print("-" * 72)
76
+ width = 100
77
+
78
+ def draw(character=None) -> None:
79
+ for index, (name, url) in enumerate(sources):
80
+ cell = rows[index] or character or ""
81
+ line = f"{name:<12} {cell:<16} {url}"
82
+ print(line.ljust(width))
83
+
84
+ for _ in sources:
85
+ for index, (name, url) in enumerate(sources):
86
+ print(f"{name:<12} {'':<16} {url}".ljust(width))
87
+
88
+ started = time.monotonic()
89
+ frames = itertools.cycle("|/-\\")
90
+ sys.stdout.write("\x1b[?25l")
91
+ try:
92
+ while True:
93
+ pending = [index for index, value in enumerate(rows) if value is None]
94
+ elapsed = time.monotonic() - started
95
+ if not pending and elapsed >= minimum:
96
+ break
97
+ sys.stdout.write(f"\x1b[{len(sources)}A")
98
+ for index, (name, url) in enumerate(sources):
99
+ cell = rows[index] or next(frames)
100
+ print(f"{name:<12} {cell:<16} {url}".ljust(width))
101
+ sys.stdout.flush()
102
+ time.sleep(0.12)
103
+ sys.stdout.write(f"\x1b[{len(sources)}A")
104
+ for index, (name, url) in enumerate(sources):
105
+ print(f"{name:<12} {rows[index] or 'not found':<16} {url}".ljust(width))
106
+ sys.stdout.flush()
107
+ finally:
108
+ sys.stdout.write("\x1b[?25h")
109
+ sys.stdout.flush()
110
+ return [(name, url, rows[index]) for index, (name, url) in enumerate(sources)]
111
+
112
+
113
+ def query_all(package: str, spinner: bool = False) -> List[Tuple[str, str, Optional[str]]]:
114
+ sources = get_sources()
115
+ if spinner and sys.stdout.isatty():
116
+ return _stream_table(package, sources)
117
+ return [(name, url, query_source(package, url)) for name, url in sources]
118
+
119
+
120
+ def _version_key(value: Optional[str]) -> Tuple[int, ...]:
121
+ if not value:
122
+ return ()
123
+ try:
124
+ from packaging.version import Version
125
+ return tuple(Version(value).release)
126
+ except Exception:
127
+ return tuple(int(p) for p in re.findall(r"\d+", value)[:4])
128
+
129
+
130
+ def best_source(package: str) -> Optional[Tuple[str, str, str]]:
131
+ """Return (name, url, version) for the index with the newest version."""
132
+ found = [(name, url, version) for name, url, version in query_all(package) if version]
133
+ if not found:
134
+ return None
135
+ return max(found, key=lambda item: _version_key(item[2]))
136
+
137
+
138
+ def print_report(package: str, rows: Optional[List[Tuple[str, str, Optional[str]]]] = None, show_package: bool = True) -> None:
139
+ rows = rows if rows is not None else query_all(package)
140
+ if show_package:
141
+ print(f"Package: {package}")
142
+ print(f"{'Source':<12} {'Version':<16} URL")
143
+ print("-" * 72)
144
+ for name, url, version in rows:
145
+ print(f"{name:<12} {version or 'not found':<16} {url}")
146
+
147
+
148
+ def handle_sources(package: str) -> int:
149
+ print_report(package)
150
+ return 0
@@ -1,36 +1,31 @@
1
+ import contextlib
2
+ import itertools
1
3
  import locale
2
4
  import subprocess
3
5
  import sys
6
+ import threading
7
+ import time
4
8
  from typing import Optional, Tuple
5
9
 
6
10
 
7
11
  def detect_language() -> str:
8
12
  """检测系统语言"""
9
- try:
10
- lang = locale.getdefaultlocale()[0]
11
- if lang:
12
- if lang.startswith("zh"):
13
- return "zh-CN"
14
- elif lang.startswith("en"):
15
- return "en-US"
16
- except Exception:
17
- pass
18
- return "en-US"
13
+ from .i18n import detect_language as _detect
14
+ return _detect()
19
15
 
20
16
 
21
17
  def get_system_language(config_lang: str = "auto") -> str:
22
18
  """获取最终使用的语言"""
23
- if config_lang == "auto":
24
- return detect_language()
25
- return config_lang
19
+ from .i18n import get_language
20
+ return get_language(config_lang)
26
21
 
27
22
 
28
23
  def run_pip_command(args: list, scope: str = "user") -> Tuple[bool, str, str]:
29
24
  """执行 pip 命令"""
30
25
  cmd = [sys.executable, "-m", "pip"]
31
- if scope == "user":
32
- cmd.append("--user")
33
26
  cmd.extend(args)
27
+ if scope == "user" and len(cmd) > 3:
28
+ cmd.insert(4, "--user")
34
29
 
35
30
  try:
36
31
  result = subprocess.run(
@@ -46,6 +41,38 @@ def run_pip_command(args: list, scope: str = "user") -> Tuple[bool, str, str]:
46
41
  return False, "", str(e)
47
42
 
48
43
 
44
+ @contextlib.contextmanager
45
+ def spinner(label: str = "", minimum: float = 1.5):
46
+ """Print a label and animate a one-line spinner for at least minimum seconds."""
47
+ if label:
48
+ print(label, flush=True)
49
+ if not sys.stdout.isatty():
50
+ yield
51
+ return
52
+
53
+ stop = threading.Event()
54
+
55
+ def animate() -> None:
56
+ for char in itertools.cycle("-\\|/"):
57
+ if stop.is_set():
58
+ break
59
+ print(f"\r{char}", end="", flush=True)
60
+ time.sleep(0.12)
61
+
62
+ thread = threading.Thread(target=animate, daemon=True)
63
+ thread.start()
64
+ started = time.monotonic()
65
+ try:
66
+ yield
67
+ remaining = minimum - (time.monotonic() - started)
68
+ if remaining > 0:
69
+ time.sleep(remaining)
70
+ finally:
71
+ stop.set()
72
+ thread.join(timeout=1)
73
+ print("\r" + " " * 8 + "\r", end="", flush=True)
74
+
75
+
49
76
  def get_pip_packages() -> list:
50
77
  """获取所有已安装的 pip 包"""
51
78
  try:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: silentstudio
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: SilentStudio CLI - 让开发者体验更好一点
5
5
  Home-page: https://github.com/Silent-Studio-CN/SilentStudioCLI
6
6
  Author: SilentStudio
@@ -230,6 +230,14 @@ silentstudio requests
230
230
 
231
231
  ---
232
232
 
233
+ 也可以通过 `ss install <包名>` 安装;安装时会流式显示各源版本,并提示选择源:
234
+
235
+ ```bash
236
+ ss install pyqt6
237
+ ```
238
+
239
+ 支持输入编号(1-4)、源名称(如 tencent,忽略大小写),或直接回车自动选择最新源。
240
+
233
241
  ### 5. 列出已安装的库
234
242
 
235
243
  ```bash
@@ -258,8 +266,37 @@ ss install list
258
266
 
259
267
  ---
260
268
 
269
+ ### 6. 多源版本查询
270
+
271
+ ```bash
272
+ ss sources silentstudio
273
+ ```
274
+
275
+ 同时查询 PyPI、阿里云、清华、腾讯云等索引,显示每个源的最新版本:
276
+
277
+ ```text
278
+ Package: silentstudio
279
+ Source Version URL
280
+ ------------------------------------------------------------------------
281
+ PyPI 0.3.1 https://pypi.org/simple
282
+ Aliyun 0.1.7 https://mirrors.aliyun.com/pypi/simple
283
+ Tsinghua 0.1.7 https://pypi.tuna.tsinghua.edu.cn/simple
284
+ Tencent 0.1.7 https://mirrors.cloud.tencent.com/pypi/simple
285
+ ```
286
+
287
+ `ss install <包名>` 会先打印同样的源版本表,然后自动选择版本最新的源安装;如果失败,会按顺序回退到其他源。
288
+
289
+ ---
290
+
261
291
  ## 🔧 配置
262
292
 
293
+ ```bash
294
+ ss config # 查看全部配置
295
+ ss config install # 交互式修改安装范围
296
+ ss config language ja # 修改语言
297
+ ```
298
+
299
+
263
300
  SilentStudio 在用户目录下创建 `~/.silentstudio/` 文件夹:
264
301
 
265
302
  ```
@@ -6,11 +6,14 @@ src/silentstudio/__init__.py
6
6
  src/silentstudio/__main__.py
7
7
  src/silentstudio/cli.py
8
8
  src/silentstudio/config.py
9
+ src/silentstudio/config_cli.py
10
+ src/silentstudio/i18n.py
9
11
  src/silentstudio/installer.py
10
12
  src/silentstudio/list_packages.py
11
13
  src/silentstudio/platform.py
12
14
  src/silentstudio/project_new.py
13
15
  src/silentstudio/release.py
16
+ src/silentstudio/sources.py
14
17
  src/silentstudio/utils.py
15
18
  src/silentstudio.egg-info/PKG-INFO
16
19
  src/silentstudio.egg-info/SOURCES.txt
File without changes
File without changes