bcmd 0.3.4__py3-none-any.whl → 0.4.6__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,52 @@ 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
+ isForceBase: bool = typer.Option(False, '--force-base', help='是否强制使用基础库去安装'),
31
+ isFullBase: bool = typer.Option(False, '--full-base', help='是否先清空venv目录再使用基础库去安装'),
28
32
  ):
29
33
  'python 虚拟环境配置'
34
+ btask.check(not (isForceBase == isFullBase == True), '不能同时使用 --force-base 和 --full-base')
30
35
  path = path or Path(os.getcwd())
31
36
  binPath = path / 'bin'
32
37
  binListFile = bpath.get(path, 'bin.list')
38
+ venvPath = bpath.get(path, 'venv')
39
+ checkPathOrNotExists(venvPath)
40
+ venvFile = bpath.get(path, '.venv')
41
+ checkFileOrNotExists(venvFile)
33
42
  await _inputQiniuPassword(binListFile, binPath)
43
+ if isFullBase:
44
+ bpath.remove(venvPath)
45
+ btask.check(not venvPath.exists(), f'无法删除 venv 目录 {venvPath}')
34
46
  packages = packages or []
35
47
  for i in range(len(packages)):
36
48
  package = packages[i]
37
49
  if package.endswith('==now'):
38
50
  ary = package.split('==')
39
51
  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
52
  if not venvPath.exists():
45
53
  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
54
+ if not venvFile.exists():
55
+ await bfile.writeText(venvFile, '')
56
+ basePackages, lockPackages = await getPackageList(venvFile)
57
+ if isForceBase or isFullBase:
58
+ installPackages = _mergePackageList(basePackages, packages)
56
59
  else:
57
- targetFile = venvListFile
60
+ installPackages = _mergePackageList(lockPackages or basePackages, packages)
61
+ installPackages = sorted(list(set(installPackages)))
58
62
  if sys.platform.startswith('win'):
59
63
  pip = bpath.get(venvPath, 'Scripts/pip.exe')
60
64
  else:
61
65
  pip = bpath.get(venvPath, 'bin/pip')
62
- await pipInstall(pip, targetFile, disabled_mirror)
63
- await bexecute.run(f'{pip} freeze > {venvLockFile}')
66
+ await _pipInstall(pip, installPackages, isOfficial)
67
+ with bpath.useTempFile() as tempFile:
68
+ await bexecute.run(f'{pip} freeze > {tempFile}')
69
+ basePackages = _mergePackageList(basePackages, packages)
70
+ lockPackages = (await bfile.readText(tempFile)).strip().split('\n')
71
+ await updatePackageList(venvFile, basePackages, lockPackages)
72
+
64
73
  # 下载 bin 文件
65
74
  if binListFile.exists():
66
75
  bin.download(
@@ -69,45 +78,72 @@ async def venv(
69
78
  output=binPath,
70
79
  )
71
80
  # 新建项目
72
- if new_project:
81
+ if isNewProject:
73
82
  with importlib.resources.path('bcmd.resources', 'project') as sourceProjectPath:
74
83
  for p in bpath.listPath(sourceProjectPath):
75
84
  bpath.copy(p, path / p.name)
76
85
  bcolor.printGreen('OK')
77
86
 
78
87
 
79
- async def pipInstall(pip: Path, file: Path, disabled_mirror: bool):
88
+ async def _pipInstall(pip: Path, installPackages: list[str], disabled_mirror: bool):
80
89
  python = pip.with_stem('python')
81
- btask.check(python.is_file(), '无法找到指定文件', python)
82
- btask.check(pip.is_file(), '无法找到指定文件', pip)
90
+ btask.check(python.is_file(), f'无法找到指定文件 {python}')
91
+ btask.check(pip.is_file(), f'无法找到指定文件 {pip}')
83
92
  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}'), '执行失败')
93
+ with bpath.useTempFile() as file:
94
+ await bfile.writeText(file, '\n'.join(installPackages))
95
+ table = PrettyTable()
96
+ table.add_column(
97
+ bcolor.yellow('#'),
98
+ [x + 1 for x in range(len(installPackages))],
99
+ )
100
+ table.add_column(
101
+ bcolor.yellow('安装库'),
102
+ [x for x in installPackages],
103
+ 'l',
104
+ )
105
+ print(table.get_string())
106
+
107
+ btask.check(
108
+ not await bexecute.run(f'{python} -m pip install --upgrade pip {indexUrl}'),
109
+ '更新 pip 失败',
110
+ )
111
+ btask.check(
112
+ not await bexecute.run(f'{pip} install -r {file} {indexUrl}'),
113
+ '执行失败',
114
+ )
115
+
86
116
 
117
+ async def _getPackageDict(venvFile: Path):
118
+ content = await bfile.readText(venvFile)
119
+ pattern = r'\[\[ (.*?) \]\]\n(.*?)(?=\n\[\[|\Z)'
120
+ matches: list[tuple[str, str]] = re.findall(pattern, content.strip(), re.DOTALL)
121
+ return {match[0]: [line.strip() for line in match[1].strip().split('\n') if line.strip()] for match in matches}
87
122
 
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
123
 
124
+ _baseName: Final[str] = 'venv'
96
125
 
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
126
 
127
+ def _getLockName():
128
+ systemName = platform.system()
129
+ return f'{_baseName}-{systemName}'
104
130
 
105
- def assertFile(file: Path):
106
- btask.check(file.is_file() or not file.exists(), '必须是文件', file)
107
131
 
132
+ async def getPackageList(venvFile: Path):
133
+ result = await _getPackageDict(venvFile)
134
+ lockName = _getLockName()
135
+ return result.get(_baseName, []), result.get(lockName, [])
108
136
 
109
- def assertPath(folder: Path):
110
- btask.check(folder.is_dir() or not folder.exists(), '必须是目录', folder)
137
+
138
+ async def updatePackageList(venvFile: Path, packages: list[str], lockPackages: list[str]):
139
+ packageDict = await _getPackageDict(venvFile)
140
+ lockName = _getLockName()
141
+ packages.sort(key=lambda x: x.lower())
142
+ lockPackages.sort(key=lambda x: x.lower())
143
+ packageDict[_baseName] = packages
144
+ packageDict[lockName] = lockPackages
145
+ content = '\n'.join([f'\n[[ {key} ]]\n{'\n'.join(value)}' for key, value in packageDict.items()]).strip()
146
+ await bfile.writeText(venvFile, content)
111
147
 
112
148
 
113
149
  async def _getPackageLatestVersion(package: str):
@@ -118,6 +154,26 @@ async def _getPackageLatestVersion(package: str):
118
154
  return data['info']['version']
119
155
 
120
156
 
157
+ def _mergePackageList(basePackages: list[str], addPackages: list[str]):
158
+ basePackagesDict = {_getPackageName(x): x for x in basePackages}
159
+ addPackagesDict = {_getPackageName(x): x for x in addPackages}
160
+ packagesDict = basePackagesDict | addPackagesDict
161
+ return sorted([x for x in packagesDict.values()])
162
+
163
+
164
+ def _getPackageName(package: str):
165
+ if '==' in package:
166
+ package = package.split('==')[0]
167
+ elif '>' in package:
168
+ package = package.split('>')[0]
169
+ elif '<' in package:
170
+ package = package.split('<')[0]
171
+ package = package.strip()
172
+ if package.startswith('#'):
173
+ package = package.replace('#', '', 1).strip()
174
+ return package
175
+
176
+
121
177
  async def _inputQiniuPassword(binListFile: Path, binPath: Path) -> None:
122
178
  '根据需要输入七牛云密码'
123
179
  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.6
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=U4Ac2B3jFFwGhzeuFdgNJ94WQ88dAJp71ffoCKbEsXU,6800
26
+ bcmd-0.4.6.dist-info/METADATA,sha256=PqZPpz2uBfhb7z-gf48uH_UZkY508_mGMsRpMfdvIOs,486
27
+ bcmd-0.4.6.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
28
+ bcmd-0.4.6.dist-info/entry_points.txt,sha256=rHJrP6KEQpB-YaQqDFzEL2v88r03rxSfnzAayRvAqHU,39
29
+ bcmd-0.4.6.dist-info/top_level.txt,sha256=-KrvhhtBcYsm4XhcjQvEcFbBB3VXeep7d3NIfDTrXKQ,5
30
+ bcmd-0.4.6.dist-info/RECORD,,
File without changes