diff --git a/.gitignore b/.gitignore index e256c7a..51d302c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ build/ dist/ pmpt.egg-info/ -*.tar.gz +*.tar.g *.pyc +*.whl __pycache__/ \ No newline at end of file diff --git a/pmpt/__init__.py b/pmpt/__init__.py index 38df8b5..5141b31 100644 --- a/pmpt/__init__.py +++ b/pmpt/__init__.py @@ -4,6 +4,7 @@ from . import util from moyanlib import jsons from rich.table import Table from . import source as sou +from . import environment as environ from . import install as installs from . import search as searchs @@ -12,6 +13,7 @@ def cli(): try: import pip except ImportError: + util.logger.critical('没有pip') util.console.print('❌ [red]pip module not found![/red]') exit(1) util.init() # 初始化 @@ -92,5 +94,9 @@ def removes(*args,**kwargs): def modifys(*args,**kwargs): sou.modify(*args,**kwargs) +@cli.command() +def version(): + environ.main() + if __name__ == '__main__': cli() \ No newline at end of file diff --git a/pmpt/environment.py b/pmpt/environment.py index af77862..af39ab5 100644 --- a/pmpt/environment.py +++ b/pmpt/environment.py @@ -1,5 +1,7 @@ import subprocess import re +from . import util +import moyanlib def get_version(command): try: @@ -10,9 +12,9 @@ def get_version(command): if version_match: return version_match.group(1) else: - return False + return '[red]False[/red]' except subprocess.CalledProcessError: - return False + return '[red]False[/red]' def getGCCver(): # 检查是否能执行 gcc 命令 @@ -33,9 +35,18 @@ def getRustVer(): rustVer = stdout.decode().split(' ')[1] return rustVer else: - return False + return '[red]False[/red]' -print("GCC 版本:", getGCCver()) -print("Clang 版本:", getClangVer()) -print("MSVC 版本:", getMSVCver()) -print('Rust版本:',getRustVer()) \ No newline at end of file +def getPIPver(): + return get_version('pip -V') +def main(): + info = moyanlib.getInfo() + printText = f'''[white]PMPT {util.__version__}[/white] +{info['OS']['Name']} {info['OS']['Version']} +Python Version: {info['Python']['Version']} +PIP Version: [green]{getPIPver()}[/green] +GCC Version: [green]{getGCCver()}[/green] +Clang Version: [green]{getClangVer()}[/green] +MSVC Version: [green]{getMSVCver()}[/green] +Rust Version: [green]{getRustVer()}[/green]''' + util.console.print(printText) \ No newline at end of file diff --git a/pmpt/install.py b/pmpt/install.py index 05e2bbf..b0be5bb 100644 --- a/pmpt/install.py +++ b/pmpt/install.py @@ -1,11 +1,21 @@ from . import util +import requests from rich.table import Table +from urllib import parse def search(name): util.loadIndex() #加载索引 for Index in util.IndexList: dt = Index.packageList.get(name,None) if dt: + try: + rurl = parse.urljoin(Index.IndexURL,name) + r = requests.get(rurl) + except: + continue + else: + if r.status_code != 200: + continue return Index.IndexURL @@ -18,6 +28,7 @@ def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes,comma packsInfo = {} with console.status('🚀🔍 Searching for package information...') as status: + # 创建表格 table = Table(show_header=True,header_style='bold') table.add_column("Package Name", width=20,style='bold') table.add_column("Package Source", width=20,style='green') diff --git a/pmpt/source.py b/pmpt/source.py index 1ba56b5..2eb14b2 100644 --- a/pmpt/source.py +++ b/pmpt/source.py @@ -4,20 +4,26 @@ import os from rich.table import Table from . import util -def line_search(li, val): +def line_search(li, val,key): + # 线性搜索算法 n = 0 for i in li: print(i) - if i['id'] == val: + if i[key] == val: return i,n n += 1 return None def add(url,priority): - sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) - if url in sourceList: + ''' + 添加源 + ''' + sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) # 加载source源 + + if not line_search(sourceList,url,'url'): # 判断源是否存在 util.console.print('❌ [red]The source already exists[/red]') exit(1) + sourceList.append({ 'url':url, 'id':str(uuid.uuid4())[:8], @@ -28,12 +34,17 @@ def add(url,priority): def lists(): + ''' + 列出所有源 + ''' sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) + # 构建table table = Table(show_header=True) table.add_column("ID",width=6) table.add_column('Priority',width=8) table.add_column('URL',width=25) + # 遍历source列表 for i in sourceList: table.add_row( i['id'], @@ -43,12 +54,15 @@ def lists(): util.console.print(table) def remove(ids,yes): + ''' + 删除 + ''' if not ids: lists() ids = util.console.input('Please enter the source sequence number to be deleted:') sourceList:list = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) - source,n = line_search(sourceList,ids) + source,n = line_search(sourceList,ids,'id') if not source: util.console.print('❌ [red]The source for this ID does not exist[/red]') @@ -71,11 +85,18 @@ def remove(ids,yes): jsons.dump(sourceList,open(os.path.join(util.dirs.user_config_dir,'Source.json'),'w')) def modify(ids,key,val): + ''' + 修改 + ''' sourceList:list = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) - source,n = line_search(sourceList,ids) + source,n = line_search(sourceList,ids,'id') + if not source: util.console.print('❌ [red]The source for this ID does not exist[/red]') + if key not in ['url','priority']: util.console.print('❌ [red]The item is not allowed to be modified or does not exist.[/red]') + sourceList[n][key] = val + jsons.dump(sourceList,open(os.path.join(util.dirs.user_config_dir,'Source.json'),'w')) \ No newline at end of file diff --git a/pmpt/util.py b/pmpt/util.py index 992943e..f1235e7 100644 --- a/pmpt/util.py +++ b/pmpt/util.py @@ -2,10 +2,9 @@ import os from subprocess import Popen import sys -import pathlib import dill from rich.console import Console -import time +from loguru import logger import subprocess from moyanlib import jsons from platformdirs import PlatformDirs @@ -15,11 +14,35 @@ IndexList = [] console = Console() def getVer(baseVar): - baseVar = baseVar + '.' + os.environ.get('GITHUB_RUN_ID', str(int(time.time()))[:6]) + baseVar = baseVar # + '.' + os.environ.get('GITHUB_RUN_ID', str(int(time.time()))[:6]) + logger.info('PMPT '+baseVar) return baseVar + +def GlobalDecorator(frame, event, arg): + if event == 'call': + try: + func_name = frame.f_code.co_name + module_name = frame.f_globals['__name__'] + package_name = module_name.split('.')[0] # 假设包名为模块名的第一部分 + if package_name == 'pmpt': + logger.trace(f"调用函数 {module_name}.{func_name}") + except: + pass + return GlobalDecorator -__version__ = getVer('1.0.1') +sys.settrace(GlobalDecorator) + +logger.remove() +logger.add( + os.path.join(dirs.user_data_dir,'log.log'), + level='TRACE', +) + +__version__ = getVer('1.0.3') + + def init(): + os.makedirs(dirs.user_data_dir,exist_ok=True) os.makedirs(os.path.join(dirs.user_data_dir,'Index'),exist_ok=True) os.makedirs(dirs.user_config_dir,exist_ok=True) @@ -41,17 +64,21 @@ def loadIndex(): sourceList = bubbleSort(sourceList) for source in sourceList: if not os.path.exists(os.path.join(dirs.user_data_dir,'Index',source['id']+'.pidx')): + logger.warning(source['url']+'没有索引') console.print(f'⚠️ [yellow]{source["url"]} did not create an index.[/yellow]') continue + logger.debug(source) IndexFile = dill.load(open(os.path.join(dirs.user_data_dir,'Index',source['id']+'.pidx'),'rb')) # 加载索引 IndexList.append(IndexFile) if len(IndexList) == 0: + raise FileNotFoundError('No index. Run "pmpt update" first to update the index') def runpip(command,other=None,dbg=False,out=True) -> Popen: ''' 运行pip ''' + logger.trace('调用runpip') if not other: other = [] baseCommand = [sys.executable,'-m','pip'] @@ -60,13 +87,15 @@ def runpip(command,other=None,dbg=False,out=True) -> Popen: Command = baseCommand + other if dbg: console.print('Command to be run:',' '.join(Command)) - + logger.debug(' ',) runClass = Popen(Command,stdout=subprocess.PIPE,stderr=subprocess.PIPE) if out: for line in iter(runClass.stdout.readline, b''): # 在这里你可以对每一行输出进行处理 line = line.decode('utf-8').strip() # 将字节转换为字符串并去除换行符 console.print(line) + if runClass.returncode != 0: + console.print(runClass.stderr.read().decode()) runClass.communicate() else: runClass.wait() diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..e69de29 diff --git a/requirements.txt b/requirements.txt index f935e70..3c17a59 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,5 @@ moyanlib click dill tqdm -rich \ No newline at end of file +rich +loguru \ No newline at end of file diff --git a/setup.py b/setup.py index 90b241a..befda45 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ setup( author='MoYan', # 作者 author_email='moyan@moyanjdc.top', # 作者邮箱 description='A Python Package Advanced Manager', # 包的简要描述 - long_description='A longer description of your package', # 包的详细描述 + long_description=open("readme.md").read(), # 包的详细描述 long_description_content_type='text/markdown', # 描述的内容类型 classifiers=[ # 包的分类信息 'Development Status :: 3 - Alpha',