bcmd 0.3.4__py3-none-any.whl → 0.4.7__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 bcmd might be problematic. Click here for more details.

bcmd/common/func.py ADDED
@@ -0,0 +1,11 @@
1
+ from pathlib import Path
2
+
3
+ from beni import btask
4
+
5
+
6
+ def checkFileOrNotExists(file: Path):
7
+ btask.check(file.is_file() or not file.exists(), f'必须是文件 {file}')
8
+
9
+
10
+ def checkPathOrNotExists(folder: Path):
11
+ btask.check(folder.is_dir() or not folder.exists(), f'必须是目录 {folder}')
@@ -8,69 +8,4 @@
8
8
  "venv": true,
9
9
  },
10
10
  "python.defaultInterpreterPath": "${workspaceFolder}/venv/Scripts/python.exe",
11
- // coommon ------------------------------------------------------------------------------------
12
- "window.menuBarVisibility": "classic", // 顶部中间
13
- // "breadcrumbs.enabled": false, // 代码顶部导航
14
- // "http.proxy": "http://localhost:15236",
15
- "security.workspace.trust.enabled": false,
16
- "redhat.telemetry.enabled": false,
17
- "window.restoreWindows": "none",
18
- "workbench.startupEditor": "none",
19
- "files.eol": "\n",
20
- "explorer.autoReveal": false, // 取消文件自动定位跟踪
21
- "editor.renderWhitespace": "none", // 不高亮显示空白
22
- "editor.unicodeHighlight.allowedLocales": { // 注释里的全角符号不提示警告
23
- "zh-hans": true,
24
- "zh-hant": true,
25
- },
26
- "github.copilot.enable": {
27
- "*": true,
28
- "plaintext": true,
29
- "markdown": true,
30
- "scminput": false,
31
- "yaml": true
32
- },
33
- "github.copilot.editor.enableAutoCompletions": true,
34
- "github.copilot.chat.localeOverride": "zh-CN",
35
- "git.openRepositoryInParentFolders": "never",
36
- "workbench.colorTheme": "Default Dark+",
37
- "editor.stickyScroll.enabled": false,
38
- "workbench.editor.enablePreview": false,
39
- "window.commandCenter": false,
40
- "editor.inlineSuggest.enabled": true,
41
- "[markdown]": {
42
- "editor.defaultFormatter": "yzhang.markdown-all-in-one"
43
- },
44
- // python -------------------------------------------------------------------------------------
45
- "python.languageServer": "Pylance",
46
- "python.analysis.autoImportCompletions": true,
47
- "python.analysis.diagnosticMode": "workspace", // 针对整个workspace做检查提示
48
- "python.analysis.typeCheckingMode": "strict",
49
- "[python]": {
50
- "editor.defaultFormatter": "ms-python.autopep8",
51
- },
52
- "autopep8.args": [
53
- "--ignore=E501",
54
- ],
55
- "python.testing.pytestArgs": [
56
- "test", // 指定单元测试查找的目录
57
- "-s", // 支持print输出
58
- ],
59
- "python.testing.unittestEnabled": false,
60
- "python.testing.pytestEnabled": false,
61
- "python.analysis.diagnosticSeverityOverrides": {
62
- "reportMissingTypeStubs": "none",
63
- "reportUnknownMemberType": "none",
64
- // "reportUnknownParameterType": "none",
65
- // "reportUnknownVariableType": "none",
66
- // "reportUnknownArgumentType": "none",
67
- // "reportMatchNotExhaustive": "none", // match 没有匹配所有,会提示添加一个 _
68
- // "reportUnusedCallResult": "warning",
69
- "reportUnusedClass": "warning",
70
- "reportUnusedCoroutine": "warning",
71
- "reportUnusedFunction": "warning",
72
- "reportUnusedImport": "warning",
73
- "reportUnusedVariable": "warning",
74
- "reportImportCycles": "warning",
75
- },
76
11
  }
bcmd/tasks/lib.py CHANGED
@@ -7,7 +7,8 @@ import typer
7
7
  from beni import bcolor, bfile, bpath, btask
8
8
  from beni.bfunc import syncCall
9
9
 
10
- from bcmd.common import password
10
+ from ..common import password
11
+ from .venv import getPackageList
11
12
 
12
13
  app: Final = btask.newSubApp('lib 工具')
13
14
 
@@ -23,10 +24,10 @@ async def tidy_dependencies(
23
24
  workspace_path = Path.cwd()
24
25
  pyprojectTomlFile = workspace_path / 'pyproject.toml'
25
26
  btask.check(pyprojectTomlFile.is_file(), 'pyproject.toml 不存在', pyprojectTomlFile)
26
- targetVenvFileName = '.venv-lock' if with_version else '.venv'
27
- targetVenvFile = bpath.get(workspace_path, f'./{targetVenvFileName}')
28
- btask.check(targetVenvFile.is_file(), '文件不存在', targetVenvFile)
29
- libAry = (await bfile.readText(targetVenvFile)).strip().replace('\r\n', '\n').split('\n')
27
+ venvFile = bpath.get(workspace_path, f'.venv')
28
+ btask.check(venvFile.is_file(), '.venv 不存在', venvFile)
29
+ basePackages, lockPackages = await getPackageList(venvFile)
30
+ libAry = lockPackages if with_version else basePackages
30
31
  oldContent = await bfile.readText(pyprojectTomlFile)
31
32
  ignoreLibAry = _getIgnoreLibAry(oldContent)
32
33
  ignoreLibAry = sorted(list(set(ignoreLibAry) & set(libAry)))
bcmd/tasks/venv.py CHANGED
@@ -1,15 +1,19 @@
1
1
  import importlib.resources
2
2
  import os
3
+ import platform
4
+ import re
3
5
  import sys
4
6
  from pathlib import Path
5
7
  from typing import Final
6
8
 
7
9
  import typer
8
- from beni import bcolor, bexecute, bfile, bhttp, binput, bpath, btask
10
+ from beni import bcolor, bexecute, bfile, bhttp, bpath, btask
9
11
  from beni.bfunc import syncCall
10
12
  from beni.btype import Null
13
+ from prettytable import PrettyTable
11
14
 
12
15
  from bcmd.common import password
16
+ from bcmd.common.func import checkFileOrNotExists, checkPathOrNotExists
13
17
 
14
18
  from . import bin
15
19
 
@@ -20,47 +24,56 @@ app: Final = btask.app
20
24
  @syncCall
21
25
  async def venv(
22
26
  packages: list[str] = typer.Argument(None),
23
- path: Path = typer.Option(None, '--path', '-p', help='指定路径,默认当前目录'),
24
- disabled_mirror: bool = typer.Option(False, '--disabled-mirror', '-d', help='是否禁用镜像'),
25
- new_project: bool = typer.Option(False, '--new-project', '-n', help='是否新建项目'),
26
- quiet: bool = typer.Option(False, '--quiet', '-q', help='是否安静模式'),
27
- no_lock: bool = typer.Option(False, '--no-lock', help='是否不使用.venv-lock文件来安装(使用在不同系统上增量安装)'),
27
+ path: Path = typer.Option(None, '--path', help='指定路径,默认当前目录'),
28
+ isOfficial: bool = typer.Option(False, '--official', help='是否使用官方地址安装(https://pypi.org/simple)'),
29
+ isNewProject: bool = typer.Option(False, '--new-project', help='是否新建项目'),
30
+ isUseBase: bool = typer.Option(False, '--use-base', help='是否强制使用基础库去安装'),
31
+ isReBase: bool = typer.Option(False, '--re-base', help='是否先清空venv目录再使用基础库去安装'),
32
+ isUseLock: bool = typer.Option(False, '--use-lock', help='是否使用锁定库安装'),
33
+ isReLock: bool = typer.Option(False, '--re-lock', help='是否先清空venv目录再使用锁定库安装'),
28
34
  ):
29
35
  'python 虚拟环境配置'
36
+ btask.check(not (isUseBase == isReBase == isUseLock == isReLock == True), '4个选项只能选择其中一个 --use-base / --re-base / --use-lock / --re-lock')
30
37
  path = path or Path(os.getcwd())
31
38
  binPath = path / 'bin'
32
39
  binListFile = bpath.get(path, 'bin.list')
40
+ venvPath = bpath.get(path, 'venv')
41
+ checkPathOrNotExists(venvPath)
42
+ venvFile = bpath.get(path, '.venv')
43
+ checkFileOrNotExists(venvFile)
33
44
  await _inputQiniuPassword(binListFile, binPath)
45
+ if isReBase or isReLock:
46
+ bpath.remove(venvPath)
47
+ btask.check(not venvPath.exists(), f'无法删除 venv 目录 {venvPath}')
34
48
  packages = packages or []
35
49
  for i in range(len(packages)):
36
50
  package = packages[i]
37
51
  if package.endswith('==now'):
38
52
  ary = package.split('==')
39
53
  packages[i] = f'{ary[0]}=={await _getPackageLatestVersion(ary[0])}'
40
- venvPath = bpath.get(path, 'venv')
41
- assertPath(venvPath)
42
- if not venvPath.exists() and not quiet:
43
- await binput.confirm('指定目录为非venv目录,是否确认新创建?')
44
54
  if not venvPath.exists():
45
55
  await bexecute.run(f'python -m venv {venvPath}')
46
- venvLockFile = bpath.get(path, '.venv-lock')
47
- assertFile(venvLockFile)
48
- venvListFile = bpath.get(path, '.venv')
49
- assertFile(venvListFile)
50
- if not venvListFile.exists():
51
- await bfile.writeText(venvListFile, '')
52
- await tidyVenvFile(venvListFile, packages)
53
- if venvLockFile.exists() and not no_lock:
54
- await tidyVenvFile(venvLockFile, packages)
55
- targetFile = venvLockFile
56
+ if not venvFile.exists():
57
+ await bfile.writeText(venvFile, '')
58
+ basePackages, lockPackages = await getPackageList(venvFile)
59
+ if isUseBase or isReBase:
60
+ installPackages = _mergePackageList(basePackages, packages)
61
+ elif isUseLock or isReLock:
62
+ installPackages = _mergePackageList(lockPackages, packages)
56
63
  else:
57
- targetFile = venvListFile
64
+ installPackages = _mergePackageList(lockPackages or basePackages, packages)
65
+ installPackages = sorted(list(set(installPackages)))
58
66
  if sys.platform.startswith('win'):
59
67
  pip = bpath.get(venvPath, 'Scripts/pip.exe')
60
68
  else:
61
69
  pip = bpath.get(venvPath, 'bin/pip')
62
- await pipInstall(pip, targetFile, disabled_mirror)
63
- await bexecute.run(f'{pip} freeze > {venvLockFile}')
70
+ await _pipInstall(pip, installPackages, isOfficial)
71
+ with bpath.useTempFile() as tempFile:
72
+ await bexecute.run(f'{pip} freeze > {tempFile}')
73
+ basePackages = _mergePackageList(basePackages, packages)
74
+ lockPackages = (await bfile.readText(tempFile)).strip().split('\n')
75
+ await updatePackageList(venvFile, basePackages, lockPackages)
76
+
64
77
  # 下载 bin 文件
65
78
  if binListFile.exists():
66
79
  bin.download(
@@ -69,45 +82,72 @@ async def venv(
69
82
  output=binPath,
70
83
  )
71
84
  # 新建项目
72
- if new_project:
85
+ if isNewProject:
73
86
  with importlib.resources.path('bcmd.resources', 'project') as sourceProjectPath:
74
87
  for p in bpath.listPath(sourceProjectPath):
75
88
  bpath.copy(p, path / p.name)
76
89
  bcolor.printGreen('OK')
77
90
 
78
91
 
79
- async def pipInstall(pip: Path, file: Path, disabled_mirror: bool):
92
+ async def _pipInstall(pip: Path, installPackages: list[str], disabled_mirror: bool):
80
93
  python = pip.with_stem('python')
81
- btask.check(python.is_file(), '无法找到指定文件', python)
82
- btask.check(pip.is_file(), '无法找到指定文件', pip)
94
+ btask.check(python.is_file(), f'无法找到指定文件 {python}')
95
+ btask.check(pip.is_file(), f'无法找到指定文件 {pip}')
83
96
  indexUrl = '-i https://pypi.org/simple' if disabled_mirror else ''
84
- btask.check(not await bexecute.run(f'{python} -m pip install --upgrade pip {indexUrl}'), '更新 pip 失败')
85
- btask.check(not await bexecute.run(f'{pip} install -r {file} {indexUrl}'), '执行失败')
97
+ with bpath.useTempFile() as file:
98
+ await bfile.writeText(file, '\n'.join(installPackages))
99
+ table = PrettyTable()
100
+ table.add_column(
101
+ bcolor.yellow('#'),
102
+ [x + 1 for x in range(len(installPackages))],
103
+ )
104
+ table.add_column(
105
+ bcolor.yellow('安装库'),
106
+ [x for x in installPackages],
107
+ 'l',
108
+ )
109
+ print(table.get_string())
110
+
111
+ btask.check(
112
+ not await bexecute.run(f'{python} -m pip install --upgrade pip {indexUrl}'),
113
+ '更新 pip 失败',
114
+ )
115
+ btask.check(
116
+ not await bexecute.run(f'{pip} install -r {file} {indexUrl}'),
117
+ '执行失败',
118
+ )
119
+
86
120
 
121
+ async def _getPackageDict(venvFile: Path):
122
+ content = await bfile.readText(venvFile)
123
+ pattern = r'\[\[ (.*?) \]\]\n(.*?)(?=\n\[\[|\Z)'
124
+ matches: list[tuple[str, str]] = re.findall(pattern, content.strip(), re.DOTALL)
125
+ return {match[0]: [line.strip() for line in match[1].strip().split('\n') if line.strip()] for match in matches}
87
126
 
88
- async def tidyVenvFile(file: Path, packages: list[str]):
89
- packageNames = [getPackageName(x) for x in packages]
90
- ary = (await bfile.readText(file)).strip().replace('\r', '').split('\n')
91
- ary = list(filter(lambda x: getPackageName(x) not in packageNames, ary))
92
- ary.extend(packages)
93
- ary.sort()
94
- await bfile.writeText(file, '\n'.join(ary).strip())
95
127
 
128
+ _baseName: Final[str] = 'venv'
96
129
 
97
- def getPackageName(value: str):
98
- sep_ary = ['>', '<', '=']
99
- for sep in sep_ary:
100
- if sep in value:
101
- return value.split(sep)[0]
102
- return value
103
130
 
131
+ def _getLockName():
132
+ systemName = platform.system()
133
+ return f'{_baseName}-{systemName}'
104
134
 
105
- def assertFile(file: Path):
106
- btask.check(file.is_file() or not file.exists(), '必须是文件', file)
107
135
 
136
+ async def getPackageList(venvFile: Path):
137
+ result = await _getPackageDict(venvFile)
138
+ lockName = _getLockName()
139
+ return result.get(_baseName, []), result.get(lockName, [])
108
140
 
109
- def assertPath(folder: Path):
110
- btask.check(folder.is_dir() or not folder.exists(), '必须是目录', folder)
141
+
142
+ async def updatePackageList(venvFile: Path, packages: list[str], lockPackages: list[str]):
143
+ packageDict = await _getPackageDict(venvFile)
144
+ lockName = _getLockName()
145
+ packages.sort(key=lambda x: x.lower())
146
+ lockPackages.sort(key=lambda x: x.lower())
147
+ packageDict[_baseName] = packages
148
+ packageDict[lockName] = lockPackages
149
+ content = '\n'.join([f'\n[[ {key} ]]\n{'\n'.join(value)}' for key, value in packageDict.items()]).strip()
150
+ await bfile.writeText(venvFile, content)
111
151
 
112
152
 
113
153
  async def _getPackageLatestVersion(package: str):
@@ -118,6 +158,26 @@ async def _getPackageLatestVersion(package: str):
118
158
  return data['info']['version']
119
159
 
120
160
 
161
+ def _mergePackageList(basePackages: list[str], addPackages: list[str]):
162
+ basePackagesDict = {_getPackageName(x): x for x in basePackages}
163
+ addPackagesDict = {_getPackageName(x): x for x in addPackages}
164
+ packagesDict = basePackagesDict | addPackagesDict
165
+ return sorted([x for x in packagesDict.values()])
166
+
167
+
168
+ def _getPackageName(package: str):
169
+ if '==' in package:
170
+ package = package.split('==')[0]
171
+ elif '>' in package:
172
+ package = package.split('>')[0]
173
+ elif '<' in package:
174
+ package = package.split('<')[0]
175
+ package = package.strip()
176
+ if package.startswith('#'):
177
+ package = package.replace('#', '', 1).strip()
178
+ return package
179
+
180
+
121
181
  async def _inputQiniuPassword(binListFile: Path, binPath: Path) -> None:
122
182
  '根据需要输入七牛云密码'
123
183
  if binListFile.exists():
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: bcmd
3
- Version: 0.3.4
3
+ Version: 0.4.7
4
4
  Summary: Commands for Beni
5
5
  Author-email: Beni Mang <benimang@126.com>
6
6
  Maintainer-email: Beni Mang <benimang@126.com>
@@ -1,11 +1,12 @@
1
1
  bcmd/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  bcmd/main.py,sha256=1HRCHLt_jeF6ImgjG_MX9N2x9H1f6FyqTX7UADzedfA,131
3
3
  bcmd/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ bcmd/common/func.py,sha256=B5IFOcI0pfqKUNg91ry-vP-WZm9S22x7yzha1QMn2kM,296
4
5
  bcmd/common/password.py,sha256=25fA1h9ttZuUobnZ_nA0Ouhmk43etBfGeM40dgxJnFY,1347
5
6
  bcmd/resources/project/.gitignore,sha256=m8wh9WahP29_Ci866EEuj07Wfn0wnkomj7wldbxd29E,26
6
7
  bcmd/resources/project/main.py,sha256=xdskz_sf05fYA1SRMFCIxDjx8SnegxTbCmHpW86ItLs,11
7
8
  bcmd/resources/project/.vscode/launch.json,sha256=Wpghb9lW9Y1wtrjqlTbyjeejDuU8BQJmBjwsLyPRh1g,478
8
- bcmd/resources/project/.vscode/settings.json,sha256=aoy95AVsUWz-UpnY6P1Of7E_ORSSrd8cFT7YKAWVqGA,3079
9
+ bcmd/resources/project/.vscode/settings.json,sha256=Ze0dt3KkKU1IiXMRiQfjbcKdSsS7XTD9PkaQn3wgEWs,290
9
10
  bcmd/resources/project/.vscode/tasks.json,sha256=gouhpkrqiPz7v65Jw1Rz-BCYU3sSdmphzXIYCzVnoe0,1783
10
11
  bcmd/tasks/__init__.py,sha256=XDE4eW0mPkUCSK9tyg1DQRGLA7A9DuTmjq5MyUiPoXs,294
11
12
  bcmd/tasks/bin.py,sha256=rdag8IJv081CKflnJKo0IkVbi5wqBGowrl6gLMtP6Eg,3133
@@ -15,15 +16,15 @@ bcmd/tasks/debian.py,sha256=B9aMIIct3vNqMJr5hTr1GegXVf20H49C27FMvRRGIzI,3004
15
16
  bcmd/tasks/download.py,sha256=0TYdoeEkXL--GTZ8ZSnSNzh8pC42kZhrTu6WVY5e7Fo,1824
16
17
  bcmd/tasks/image.py,sha256=OSqShLb_lwa77aQOnRNksXNemtuAnQDGg-VfiDy9fEM,2310
17
18
  bcmd/tasks/json.py,sha256=WWOyvcZPYaqQgp-Tkm-uIJschNMBKPKtZN3yXz_SC5s,635
18
- bcmd/tasks/lib.py,sha256=sUITLkSJwpPSCIu3PrxKH59XLXga-DMesCWpgHYGaPg,4625
19
+ bcmd/tasks/lib.py,sha256=6-1WGYUzBtr80K7zuQETLiQKpB9EfXvPxiL22a8u5v8,4583
19
20
  bcmd/tasks/math.py,sha256=M7-mmyQPx1UW7JiU1knY5Ty0hBw9zv9L4NNJf9eEjZ4,2857
20
21
  bcmd/tasks/mirror.py,sha256=-ztGkkxVk81npIo4cpmyLdHa1w4ZFdiJ3mv5WIBMI5Y,1556
21
22
  bcmd/tasks/project.py,sha256=ESWyRvRu4tesoYrlBtYMrQvQoxzMnFkI-jTN2hsYruI,939
22
23
  bcmd/tasks/proxy.py,sha256=mdiBR2vah5qKt9o7dXE7rg8Lz_A6GheVJDts0m1gmSs,1324
23
24
  bcmd/tasks/time.py,sha256=nSIVYov2LsGdxsZAtC91UKXcUtVAqR9o-JmzeuevFhA,2586
24
- bcmd/tasks/venv.py,sha256=8AjQqxlOnw37WqwBzC2gBd8Lm4uLHcVcD7V2iPrxBpg,4672
25
- bcmd-0.3.4.dist-info/METADATA,sha256=x7eN_zToE0jwj-BTShR7Z8UTYIPH9Vop0kHmn6fv4tA,486
26
- bcmd-0.3.4.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
27
- bcmd-0.3.4.dist-info/entry_points.txt,sha256=rHJrP6KEQpB-YaQqDFzEL2v88r03rxSfnzAayRvAqHU,39
28
- bcmd-0.3.4.dist-info/top_level.txt,sha256=-KrvhhtBcYsm4XhcjQvEcFbBB3VXeep7d3NIfDTrXKQ,5
29
- bcmd-0.3.4.dist-info/RECORD,,
25
+ bcmd/tasks/venv.py,sha256=Metps2tKu_wyZfezMTvQPInAWgQV6FyRW9l4-WS9lk8,7160
26
+ bcmd-0.4.7.dist-info/METADATA,sha256=PLqFGXVEpVWeo8M0qwIik_e5dHmkL40BxC1CvIV6aPo,486
27
+ bcmd-0.4.7.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
28
+ bcmd-0.4.7.dist-info/entry_points.txt,sha256=rHJrP6KEQpB-YaQqDFzEL2v88r03rxSfnzAayRvAqHU,39
29
+ bcmd-0.4.7.dist-info/top_level.txt,sha256=-KrvhhtBcYsm4XhcjQvEcFbBB3VXeep7d3NIfDTrXKQ,5
30
+ bcmd-0.4.7.dist-info/RECORD,,
File without changes