添加makefile

This commit is contained in:
root 2024-04-03 21:12:35 +08:00
parent a135ef0e1d
commit 94642c4df5
12 changed files with 461 additions and 351 deletions

48
Makefile Normal file
View File

@ -0,0 +1,48 @@
# Makefile for Python project
# 定义变量
PYTHON := python
PMPT := python -m pmpt
PIP := pip
VENV := venv
# 定义目录
DIST_DIR := dists
BUILD_DIR := build
# 定义目标
ALL: help
help:
@echo "Available targets:"
@echo " install Install dependencies"
@echo " test Run tests"
@echo " clean Clean up"
build:
$(PYTHON) setup.py bdist_wheel -d $(DIST_DIR) sdist -d $(DIST_DIR)
init: venv
@for file in requirements/*.txt; do \
if [ -f "$$file" ]; then \
$(PIP) install -r "$$file"; \
fi; \
done
venv:
$(PYTHON) -m venv $(VENV)
cleanall: clean
rm -r $(VENV)
clean:
rm -r $(DIST_DIR) $(BUILD_DIR) pmpt.egg-info
push:
@if [ -z "$(msg)" ]; then \
echo "Please provide a commit message using 'msg' parameter."; \
exit 1; \
else \
git add .; \
git commit -m "$(msg)"; \
git push origin master; \
fi

View File

@ -1,4 +1,4 @@
#pylint:disable=W0611
# pylint:disable=W0611
import click
from . import update as updates
from . import util
@ -6,107 +6,122 @@ 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 install as installs
from . import search as searchs
import datetime
import webbrowser
import time
@click.group()
def cli():
today = datetime.datetime.today()
if today.month == 9 and today.day == 28:
webbrowser.open('https://ys.mihoyo.com/')
util.console.print('[green]Genshinactivate[/green]')
webbrowser.open("https://ys.mihoyo.com/")
util.console.print("[green]Genshinactivate[/green]")
time.sleep(0.7)
util.console.print('[green]You all must download Genshin Impact.[/green]')
util.console.print("[green]You all must download Genshin Impact.[/green]")
time.sleep(0.7)
util.console.print("Then don't use PMPT.",style='green')
util.console.print("Then don't use PMPT.", style="green")
try:
import pip
except ImportError:
util.logger.critical('没有pip')
util.console.print('❌ [red]pip module not found![/red]')
util.logger.critical("没有pip")
util.console.print("❌ [red]pip module not found![/red]")
exit(1)
@cli.command(short_help='Update Package Index')
@cli.command(short_help="Update Package Index")
def update():
# 调用更新函数
updates.getAllIndex()
@cli.command(short_help='Install Python package')
@click.argument('packlist',nargs=-1, required=True)
@click.option('--upgrade','-U',is_flag=True,default=False)
@click.option('--reads', '-r',is_flag=True,default=False)
@click.option('--force-reinstall','-fr',is_flag=True,default=False)
@click.option('--ignore-requires-python','-irp',is_flag=True,default=False)
@click.option('--yes','-y',is_flag=True,default=False)
@click.option('--command','-c',is_flag=True,default=False)
def install(*args,**kwargs):
installs.main(*args,**kwargs)
@cli.command(name='list',short_help='List all Python packages')
def listp():
@cli.command(short_help="Install Python package")
@click.argument("packlist", nargs=-1, required=True)
@click.option("--upgrade", "-U", is_flag=True, default=False)
@click.option("--reads", "-r", is_flag=True, default=False)
@click.option("--force-reinstall", "-fr", is_flag=True, default=False)
@click.option("--ignore-requires-python", "-irp", is_flag=True, default=False)
@click.option("--yes", "-y", is_flag=True, default=False)
@click.option("--command", "-c", is_flag=True, default=False)
def install(*args, **kwargs):
installs.main(*args, **kwargs)
@cli.command(name="list", short_help="List all Python packages")
def listp():
table = Table(show_header=True)
table.add_column('Name')
table.add_column('Version')
listv = util.runpip('freeze',out=False)
for line in iter(listv.stdout.readline, b''):
table.add_column("Name")
table.add_column("Version")
listv = util.runpip("freeze", out=False)
for line in iter(listv.stdout.readline, b""):
# 在这里你可以对每一行输出进行处理
line = line.decode('utf-8').strip() # 将字节转换为字符串并去除换行符
if '==' not in line or line[0]=='#':
line = line.decode("utf-8").strip() # 将字节转换为字符串并去除换行符
if "==" not in line or line[0] == "#":
continue
lineList = line.split('==')
table.add_row(lineList[0],lineList[1])
lineList = line.split("==")
table.add_row(lineList[0], lineList[1])
util.console.print(table)
@cli.command()
@click.argument('name')
@click.option('--yes','-y',is_flag=True,default=False)
def remove(name,yes):
args = []
if yes:
args.append('-y')
args.append(name)
util.runpip('uninstall',args)
@cli.command()
@click.argument('name')
@click.option('--allinfo','-a',is_flag=True,default=False)
@click.option('--api-url','-u',default=None)
@click.argument("name")
@click.option("--yes", "-y", is_flag=True, default=False)
def remove(name, yes):
args = []
if yes:
args.append("-y")
args.append(name)
util.runpip("uninstall", args)
@cli.command()
@click.argument("name")
@click.option("--allinfo", "-a", is_flag=True, default=False)
@click.option("--api-url", "-u", default=None)
def search(*args, **kwargs):
searchs.main(*args,**kwargs)
searchs.main(*args, **kwargs)
@cli.group()
def source():
pass
@source.command()
@click.argument('url')
@click.option('--priority','-p',default=1,type=int)
def add(*args,**kwargs):
sou.add(*args,**kwargs)
@source.command(name='list')
@click.argument("url")
@click.option("--priority", "-p", default=1, type=int)
def add(*args, **kwargs):
sou.add(*args, **kwargs)
@source.command(name="list")
def lists():
sou.lists()
@source.command(name='remove')
@click.argument('ids',default=None,required=False)
@click.option('-y','--yes',is_flag=True,default=False)
def removes(*args,**kwargs):
sou.remove(*args,**kwargs)
@source.command(name='modify')
@click.argument('ids')
@click.argument('key')
@click.argument('val')
def modifys(*args,**kwargs):
sou.modify(*args,**kwargs)
@source.command(name="remove")
@click.argument("ids", default=None, required=False)
@click.option("-y", "--yes", is_flag=True, default=False)
def removes(*args, **kwargs):
sou.remove(*args, **kwargs)
@source.command(name="modify")
@click.argument("ids")
@click.argument("key")
@click.argument("val")
def modifys(*args, **kwargs):
sou.modify(*args, **kwargs)
@cli.command()
def version():
environ.main()
if __name__ == '__main__':
cli()
if __name__ == "__main__":
cli()

View File

@ -1,2 +1,3 @@
import pmpt
pmpt.cli()
pmpt.cli()

View File

@ -3,50 +3,62 @@ import re
from . import util
import moyanlib
def get_version(command):
try:
# 使用 subprocess 调用系统命令获取版本信息
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True)
output = subprocess.check_output(
command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True
)
# 使用正则表达式提取版本号
version_match = re.search(r'(\d+\.\d+(\.\d+){0,2})', output)
version_match = re.search(r"(\d+\.\d+(\.\d+){0,2})", output)
if version_match:
return version_match.group(1)
else:
return '[red]False[/red]'
return "[red]False[/red]"
except subprocess.CalledProcessError:
return '[red]False[/red]'
return "[red]False[/red]"
def getGCCver():
# 检查是否能执行 gcc 命令
return get_version('gcc --version')
return get_version("gcc --version")
def getClangVer():
# 检查是否能执行 clang 命令
return get_version('clang --version')
return get_version("clang --version")
def getMSVCver():
# 检查是否能执行 cl 命令MSVC编译器
return get_version('cl')
return get_version("cl")
def getRustVer():
process = subprocess.Popen(['rustc --version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
process = subprocess.Popen(
["rustc --version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
)
stdout, stderr = process.communicate()
if process.returncode == 0:
rustVer = stdout.decode().split(' ')[1]
rustVer = stdout.decode().split(" ")[1]
return rustVer
else:
return '[red]False[/red]'
return "[red]False[/red]"
def getPIPver():
return get_version('pip -V')
return get_version("pip -V")
def main():
info = moyanlib.getInfo()
printText = f'''[white]PMPT {util.__version__}[/white]
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)
Rust Version: [green]{getRustVer()}[/green]"""
util.console.print(printText)

View File

@ -2,14 +2,14 @@ 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)
for Index in util.loadIndex():
dt = Index.packageList.get(name, None)
if dt:
try:
rurl = parse.urljoin(Index.IndexURL,name)
rurl = parse.urljoin(Index.IndexURL, name)
r = requests.get(rurl)
except:
continue
@ -17,91 +17,88 @@ def search(name):
if r.status_code != 200:
continue
return Index.IndexURL
def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes,command):
def main(
packlist, upgrade, reads, force_reinstall, ignore_requires_python, yes, command
):
console = util.console
if reads: # 从文件读取列表
if reads: # 从文件读取列表
f = open(packlist[0])
packlist = f.read().split('\n')
packlist = f.read().split("\n")
packsInfo = {}
with console.status('🚀🔍 Searching for package information...') as status:
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')
for rawpack in packlist: # 解析指定了版本的包名
if '==' in rawpack:
pack = rawpack.split('==')[0]
elif '>=' in rawpack:
pack = rawpack.split('>=')[0]
elif '<=' in rawpack:
pack = rawpack.split('<=')[0]
elif '<' in rawpack:
pack = rawpack.split('<')[0]
elif '>' in rawpack:
pack = rawpack.split('>')[0]
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")
for rawpack in packlist: # 解析指定了版本的包名
if "==" in rawpack:
pack = rawpack.split("==")[0]
elif ">=" in rawpack:
pack = rawpack.split(">=")[0]
elif "<=" in rawpack:
pack = rawpack.split("<=")[0]
elif "<" in rawpack:
pack = rawpack.split("<")[0]
elif ">" in rawpack:
pack = rawpack.split(">")[0]
else:
pack = rawpack
result = search(pack.lower()) # 转小写并获取源地址
packsInfo[pack] = [result,rawpack]
canInstallPack = []
for k,v in packsInfo.items():
result = search(pack.lower()) # 转小写并获取源地址
packsInfo[pack] = [result, rawpack]
canInstallPack = []
for k, v in packsInfo.items():
if not v[0]:
table.add_row(k, "[red]Not found[red]")
else:
table.add_row(k,v[0])
table.add_row(k, v[0])
canInstallPack.append(k)
console.print(table)
if len(canInstallPack) < 1:
console.print('❌ [red]There are no packages available for installation.[red]')
console.print("❌ [red]There are no packages available for installation.[red]")
exit(1)
console.print('📦 Packages to be installed:')
console.print(' '.join(canInstallPack))
while True: # 是否允许安装
console.print("📦 Packages to be installed:")
console.print(" ".join(canInstallPack))
while True: # 是否允许安装
if yes:
break
ye = console.input('Proceed with installation? [Y/n]: ')
if ye.lower() == 'y':
ye = console.input("Proceed with installation? [Y/n]: ")
if ye.lower() == "y":
break
elif ye.lower() == 'n':
console.print('🛑 [red]User canceled the installation.[/red]')
elif ye.lower() == "n":
console.print("🛑 [red]User canceled the installation.[/red]")
exit(1)
else:
continue
console.print('🛠️ Initiating pip installation...')
console.print("🛠️ Initiating pip installation...")
for pack in canInstallPack:
# 构建命
args = [ '-i', packsInfo[pack][0]] # 指定源
if upgrade: # 升级
args.append('-U')
if force_reinstall: # 强制重新安装
args.append('--force-reinstall')
if ignore_requires_python: # 忽略Python版本
args.append('--ignore-requires-python')
args = ["-i", packsInfo[pack][0]] # 指定源
if upgrade: # 升级
args.append("-U")
if force_reinstall: # 强制重新安装
args.append("--force-reinstall")
if ignore_requires_python: # 忽略Python版本
args.append("--ignore-requires-python")
args.append(packsInfo[pack][1])
with console.status('🚀 [green]Installing...[/green]') as status:
ret = util.runpip('install',args,command) # 运行pip
if ret.returncode != 0: #是否执行完毕
console.print('❌ [red]Installation failed.[/red]')
with console.status("🚀 [green]Installing...[/green]") as status:
ret = util.runpip("install", args, command) # 运行pip
if ret.returncode != 0: # 是否执行完毕
console.print("❌ [red]Installation failed.[/red]")
exit(1)
console.print(f'✅ [green]Installation successful for {pack}[/green]')
console.print(f"✅ [green]Installation successful for {pack}[/green]")

View File

@ -5,36 +5,36 @@ from .install import search
import os
console = util.console
def main(name,allinfo,api_url):
def main(name, allinfo, api_url):
if not search(name):
console.print('❌ [red]The package does not exist[/red]')
console.print("❌ [red]The package does not exist[/red]")
exit()
if not api_url:
api_url = open(os.path.join(util.dirs.user_config_dir,'api.url')).read()
api_url = open(os.path.join(util.dirs.user_config_dir, "api.url")).read()
req = requests.get(api_url.format(name))
if req.status_code == 404:
console.print(404 )
console.print('❌ [red]The package does not exist[/red]')
console.print(404)
console.print("❌ [red]The package does not exist[/red]")
exit()
elif req.status_code != 200:
console.print('❌ [red]Server Error![/red]')
console.print('[red]Error Code: '+str(req.status_code)+'[/red]')
console.print("❌ [red]Server Error![/red]")
console.print("[red]Error Code: " + str(req.status_code) + "[/red]")
exit()
packageInfo = jsons.loads(req.text)
packageInfo = jsons.loads(req.text)
if not allinfo:
print('Package Name:',packageInfo['info']['name'])
print('Version:',packageInfo['info']['version'])
print('Author:',packageInfo['info']['author'])
print('Summary:',packageInfo['info']['summary'])
print('Keywords:',packageInfo['info']['keywords'])
print('License:',packageInfo['info']['license'])
if packageInfo['info']['requires_dist']:
print('Dependent Library:',', '.join(packageInfo['info']['requires_dist']))
print("Package Name:", packageInfo["info"]["name"])
print("Version:", packageInfo["info"]["version"])
print("Author:", packageInfo["info"]["author"])
print("Summary:", packageInfo["info"]["summary"])
print("Keywords:", packageInfo["info"]["keywords"])
print("License:", packageInfo["info"]["license"])
if packageInfo["info"]["requires_dist"]:
print("Dependent Library:", ", ".join(packageInfo["info"]["requires_dist"]))
elif allinfo:
for k,v in packageInfo['info'].items():
print(f'{k}: {v}')
for k, v in packageInfo["info"].items():
print(f"{k}: {v}")

View File

@ -4,99 +4,112 @@ import os
from rich.table import Table
from . import util
def line_search(li, val,key):
def line_search(li, val, key):
# 线性搜索算法
n = 0
for i in li:
print(i)
if i[key] == val:
return i,n
return i, n
n += 1
return None
def add(url,priority):
'''
def add(url, priority):
"""
添加源
'''
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]')
"""
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],
'priority':priority
})
jsons.dump(sourceList,open(os.path.join(util.dirs.user_config_dir,'Source.json'),'w'))
sourceList.append({"url": url, "id": str(uuid.uuid4())[:8], "priority": priority})
jsons.dump(
sourceList, open(os.path.join(util.dirs.user_config_dir, "Source.json"), "w")
)
def lists():
'''
"""
列出所有源
'''
sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json')))
"""
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)
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'],
str(i['priority']),
i['url']
)
table.add_row(i["id"], str(i["priority"]), i["url"])
util.console.print(table)
def remove(ids,yes):
'''
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,'id')
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, "id")
if not source:
util.console.print('❌ [red]The source for this ID does not exist[/red]')
while True: # 是否允许安装
util.console.print("❌ [red]The source for this ID does not exist[/red]")
while True: # 是否允许安装
if yes:
break
ye = util.console.input('Are you sure you want to delete? [Y/n]: ')
if ye.lower() == 'y':
ye = util.console.input("Are you sure you want to delete? [Y/n]: ")
if ye.lower() == "y":
break
elif ye.lower() == 'n':
util.console.print('🛑 [red]The user exited the program[/red]')
elif ye.lower() == "n":
util.console.print("🛑 [red]The user exited the program[/red]")
exit(1)
else:
continue
sourceList.remove(source)
jsons.dump(sourceList,open(os.path.join(util.dirs.user_config_dir,'Source.json'),'w'))
def modify(ids,key,val):
'''
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,'id')
"""
sourceList: list = jsons.load(
open(os.path.join(util.dirs.user_config_dir, "Source.json"))
)
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]')
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'))
jsons.dump(
sourceList, open(os.path.join(util.dirs.user_config_dir, "Source.json"), "w")
)

View File

@ -3,58 +3,65 @@ from moyanlib import jsons
from tqdm import tqdm
import dill
import os
from .util import dirs,console
from .util import dirs, console
def getSourceID(url):
'''
"""
获取源id
'''
return url['id'] # 取前八位
"""
return url["id"] # 取前八位
class Index:
def __init__(self,indexurl):
def __init__(self, indexurl):
self.packageList = {}
self.IndexURL = indexurl['url']
self.IndexURL = indexurl["url"]
self.number = 0
self.priority = indexurl['priority']
self.priority = indexurl["priority"]
def addPackage(self, name):
self.packageList[name] = '1'
self.packageList[name] = "1"
self.number += 1
def getIndex(url):
req = requests.get(url['url']) # 请求HTML
req = requests.get(url["url"]) # 请求HTML
HTMLIndex = req.text
ClassIndex = Index(url)
console.print('🔍 Parsing HTML index...')
for line in tqdm(HTMLIndex.split('\n')):
console.print("🔍 Parsing HTML index...")
for line in tqdm(HTMLIndex.split("\n")):
# 提取并筛选标签
line_list = line.split('>')
if len(line_list) > 1 and '<a ' in line:
package_name = line_list[1].split('<')[0]
ClassIndex.addPackage(package_name) # 添加包
console.print('Total number of packages:', str(ClassIndex.number))
console.print('📚 Saving index..."')
dill.dump(ClassIndex,open(f'{dirs.user_data_dir}/Index/{getSourceID(url)}.pidx','wb'))
line_list = line.split(">")
if len(line_list) > 1 and "<a " in line:
package_name = line_list[1].split("<")[0]
ClassIndex.addPackage(package_name) # 添加包
console.print("Total number of packages:", str(ClassIndex.number))
console.print('📚 Saving index..."')
dill.dump(
ClassIndex, open(f"{dirs.user_data_dir}/Index/{getSourceID(url)}.pidx", "wb")
)
def getAllIndex():
'''
"""
SourceList = [
'https://pypi.tuna.tsinghua.edu.cn/simple',
'https://mirrors.bfsu.edu.cn/pypi/web/simple/'
]
'''
SourceList = jsons.load(open(os.path.join(dirs.user_config_dir,'Source.json'))) # 加载源列表
"""
SourceList = jsons.load(
open(os.path.join(dirs.user_config_dir, "Source.json"))
) # 加载源列表
if len(SourceList) < 1:
console.print('❌ [red]You have not configured any sources.[/red]')
console.print("❌ [red]You have not configured any sources.[/red]")
exit(1)
for source in SourceList: # 遍历源列表
console.print('📚 Downloading index from', source['url']+'...')
for source in SourceList: # 遍历源列表
console.print("📚 Downloading index from", source["url"] + "...")
getIndex(source)
console.print('✅ [green]Index downloaded successfully![/green]')
console.print("✅ [green]Index downloaded successfully![/green]")

View File

@ -1,4 +1,4 @@
#pylint:disable=W0622
# pylint:disable=W0622
import os
from subprocess import Popen
import sys
@ -8,111 +8,130 @@ from loguru import logger
import subprocess
from moyanlib import jsons
import time
import datetime
import datetime
from platformdirs import PlatformDirs
dirs = PlatformDirs("PMPT", "MoYan")
IndexList = []
console = Console()
def getVer(baseVar):
baseVar = baseVar # + '.' + os.environ.get('GITHUB_RUN_ID', str(int(time.time()))[:6])
logger.info('PMPT '+baseVar)
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':
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':
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
sys.settrace(GlobalDecorator)
sys.settrace(GlobalDecorator)
logger.remove()
logger.add(
os.path.join(dirs.user_data_dir,'log.log'),
level='TRACE',
os.path.join(dirs.user_data_dir, "log.log"),
level="TRACE",
)
__version__ = getVer('1.0.4')
__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)
os.makedirs(dirs.user_cache_dir,exist_ok=True)
if not os.path.exists(os.path.join(dirs.user_config_dir,'Source.json')):
open(os.path.join(dirs.user_config_dir,'Source.json'),'w').write('[]')
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)
os.makedirs(dirs.user_cache_dir, exist_ok=True)
if not os.path.exists(os.path.join(dirs.user_config_dir, "Source.json")):
open(os.path.join(dirs.user_config_dir, "Source.json"), "w").write("[]")
from . import source
source.add()
if not os.path.exists(os.path.join(dirs.user_config_dir,'api.url')):
open(os.path.join(dirs.user_config_dir,'api.url'),'w').write('https://pypi.org/pypi/{}/json')
if not os.path.exists(os.path.join(dirs.user_config_dir, "api.url")):
open(os.path.join(dirs.user_config_dir, "api.url"), "w").write(
"https://pypi.org/pypi/{}/json"
)
def bubbleSort(arr):
for i in range(1,len(arr)):
for j in range(0, len(arr)-i):
if arr[j]['priority'] < arr[j+1]['priority']:
for i in range(1, len(arr)):
for j in range(0, len(arr) - i):
if arr[j]["priority"] < arr[j + 1]["priority"]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def loadIndex():
'''
"""
加载索引
'''
"""
today = datetime.datetime.today()
if today.month == 4 and today.day == 1:
console.print('😱😱😱 [red]Oh no, your indexes have all been eaten by a python snake.[/red]')
console.print(
"😱😱😱 [red]Oh no, your indexes have all been eaten by a python snake.[/red]"
)
time.sleep(2.3)
console.print('😄 [green]But after our life-and-death struggle, I managed to retrieve all of your indexes.[/green]')
sourceList = jsons.load(open(os.path.join(dirs.user_config_dir,'Source.json')))
console.print(
"😄 [green]But after our life-and-death struggle, I managed to retrieve all of your indexes.[/green]"
)
sourceList = jsons.load(open(os.path.join(dirs.user_config_dir, "Source.json")))
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]')
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')
IndexFile = dill.load(
open(
os.path.join(dirs.user_data_dir, "Index", source["id"] + ".pidx"), "rb"
)
) # 加载索引
yield IndexFile
def runpip(command,other=None,dbg=False,out=True) -> Popen:
'''
def runpip(command, other=None, dbg=False, out=True) -> Popen:
"""
运行pip
'''
logger.trace('调用runpip')
"""
logger.trace("调用runpip")
if not other:
other = []
baseCommand = [sys.executable,'-m','pip']
baseCommand = [sys.executable, "-m", "pip"]
baseCommand.append(command)
Command = baseCommand + other
if dbg:
console.print('Command to be run:',' '.join(Command))
logger.debug(' ',)
runClass = Popen(Command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
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''):
for line in iter(runClass.stdout.readline, b""):
# 在这里你可以对每一行输出进行处理
line = line.decode('utf-8').strip() # 将字节转换为字符串并去除换行符
console.print(line)
line = line.decode("utf-8").strip() # 将字节转换为字符串并去除换行符
console.print(line)
if runClass.returncode != 0:
console.print(runClass.stderr.read().decode())
runClass.communicate()
else:
runClass.wait()
return runClass

0
requirements/web.txt Normal file
View File

View File

@ -2,31 +2,29 @@ from setuptools import setup, find_packages
from pmpt import util
setup(
name='pmpt', # 包的名称
name="pmpt", # 包的名称
version=util.__version__, # 版本号
packages=find_packages(), # 包含的包
author='MoYan', # 作者
author_email='moyan@moyanjdc.top', # 作者邮箱
description='A Python Package Advanced Manager', # 包的简要描述
author="MoYan", # 作者
author_email="moyan@moyanjdc.top", # 作者邮箱
description="A Python Package Advanced Manager", # 包的简要描述
long_description=open("readme.md").read(), # 包的详细描述
long_description_content_type='text/markdown', # 描述的内容类型
long_description_content_type="text/markdown", # 描述的内容类型
classifiers=[ # 包的分类信息
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
setup_requires = ['platformdirs'],
install_requires=open('requirements.txt').read().split('\n'),
setup_requires=["platformdirs"],
install_requires=open("requirements/base.txt").read().split("\n"),
entry_points={
'console_scripts': [
'pmpt=pmpt:cli'
],
"console_scripts": ["pmpt=pmpt:cli"],
},
extras_require={
'web': ["flask"],
}
"web": open("requirements/web.txt").read().split("\n"),
},
)