This commit is contained in:
root 2024-04-01 18:40:06 +08:00
parent 7925df0ca4
commit b49781cbb5
6 changed files with 164 additions and 54 deletions

View File

@ -2,11 +2,17 @@ import click
from . import update as updates from . import update as updates
from . import util from . import util
from moyanlib import jsons from moyanlib import jsons
import os from . import source as sou
from . import install as installs from . import install as installs
from . import search as searchs from . import search as searchs
@click.group() @click.group()
def cli(): def cli():
try:
import pip
except ImportError:
util.console.print('❌ [red]pip module not found![/red]')
exit(1)
util.init() # 初始化 util.init() # 初始化
@cli.command(short_help='Update Package Index') @cli.command(short_help='Update Package Index')
@ -21,6 +27,7 @@ def update():
@click.option('--force-reinstall','-fr',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('--ignore-requires-python','-irp',is_flag=True,default=False)
@click.option('--yes','-y',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): def install(*args,**kwargs):
installs.main(*args,**kwargs) installs.main(*args,**kwargs)
@ -51,18 +58,26 @@ def source():
@source.command() @source.command()
@click.argument('url') @click.argument('url')
def add(url): @click.option('--priority','-p',default=1,type=int)
sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) def add(*args,**kwargs):
if url in sourceList: sou.add(*args,**kwargs)
print('The source already exists')
exit()
sourceList.append(url)
jsons.dump(sourceList,open(os.path.join(util.dirs.user_config_dir,'Source.json')))
@source.command(name='list') @source.command(name='list')
def lists(): def lists():
sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json'))) sou.lists()
ids = 1
for i in sourceList: @source.command(name='remove')
print(str(ids)+'.',i) @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)
if __name__ == '__main__': if __name__ == '__main__':
cli() cli()

View File

@ -1,5 +1,4 @@
from . import util from . import util
from rich.console import Console
from rich.table import Table from rich.table import Table
def search(name): def search(name):
@ -9,8 +8,10 @@ def search(name):
if dt: if dt:
return Index.IndexURL return Index.IndexURL
def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes):
console = Console()
def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes,command):
console = util.console
if reads: # 从文件读取列表 if reads: # 从文件读取列表
f = open(packlist[0]) f = open(packlist[0])
packlist = f.read().split('\n') packlist = f.read().split('\n')
@ -50,7 +51,7 @@ def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes):
if len(canInstallPack) < 1: 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() exit(1)
console.print('📦 Packages to be installed:') console.print('📦 Packages to be installed:')
console.print(' '.join(canInstallPack)) console.print(' '.join(canInstallPack))
@ -65,7 +66,7 @@ def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes):
break break
elif ye.lower() == 'n': elif ye.lower() == 'n':
console.print('🛑 [red]User canceled the installation.[/red]') console.print('🛑 [red]User canceled the installation.[/red]')
exit() exit(1)
else: else:
continue continue
@ -83,11 +84,12 @@ def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes):
args.append('--ignore-requires-python') args.append('--ignore-requires-python')
args.append(packsInfo[pack][1]) args.append(packsInfo[pack][1])
ret = util.runpip('install',args) # 运行pip with console.status('🚀 [green]Installing...[/green]') as status:
ret = util.runpip('install',args,command) # 运行pip
if ret.returncode != 0: #是否执行完毕 if ret.returncode != 0: #是否执行完毕
console.print('❌ [red]Installation failed.[/red]') console.print('❌ [red]Installation failed.[/red]')
exit() exit(1)
console.print(f'✅ [green]Installation successful for {pack}[/green]') console.print(f'✅ [green]Installation successful for {pack}[/green]')

View File

@ -3,9 +3,8 @@ from . import util
from moyanlib import jsons from moyanlib import jsons
from .install import search from .install import search
import os import os
from rich.console import Console
console = Console() console = util.console
def main(name,allinfo,api_url): def main(name,allinfo,api_url):
if not search(name): if not search(name):
console.print('❌ [red]The package does not exist[/red]') console.print('❌ [red]The package does not exist[/red]')
@ -16,6 +15,7 @@ def main(name,allinfo,api_url):
req = requests.get(api_url.format(name)) req = requests.get(api_url.format(name))
if req.status_code == 404: if req.status_code == 404:
console.print(404 )
console.print('❌ [red]The package does not exist[/red]') console.print('❌ [red]The package does not exist[/red]')
exit() exit()
elif req.status_code != 200: elif req.status_code != 200:
@ -32,6 +32,7 @@ def main(name,allinfo,api_url):
print('Summary:',packageInfo['info']['summary']) print('Summary:',packageInfo['info']['summary'])
print('Keywords:',packageInfo['info']['keywords']) print('Keywords:',packageInfo['info']['keywords'])
print('License:',packageInfo['info']['license']) print('License:',packageInfo['info']['license'])
if packageInfo['info']['requires_dist']:
print('Dependent Library:',', '.join(packageInfo['info']['requires_dist'])) print('Dependent Library:',', '.join(packageInfo['info']['requires_dist']))
elif allinfo: elif allinfo:
for k,v in packageInfo['info'].items(): for k,v in packageInfo['info'].items():

81
pmpt/source.py Normal file
View File

@ -0,0 +1,81 @@
import uuid
from moyanlib import jsons
import os
from rich.table import Table
from . import util
def line_search(li, val):
n = 0
for i in li:
print(i)
if i['id'] == 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:
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'))
def lists():
sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json')))
table = Table(show_header=True)
table.add_column("ID",width=6)
table.add_column('Priority',width=8)
table.add_column('URL',width=25)
for i in sourceList:
table.add_row(
i['id'],
str(i['priority']),
i['url']
)
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)
if not source:
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':
break
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):
sourceList:list = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json')))
source,n = line_search(sourceList,ids)
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'))

View File

@ -3,34 +3,27 @@ from moyanlib import jsons
from tqdm import tqdm from tqdm import tqdm
import dill import dill
import os import os
import urllib.parse as urlparse from .util import dirs,console
from hashlib import sha256
from .util import dirs
from rich.console import Console
console = Console()
def getSourceID(url): def getSourceID(url):
''' '''
获取源id 获取源id
''' '''
url = urlparse.urlparse(url) return url['id'] # 取前八位
SourceID_Str = url.netloc + url.path # 取主机名和路径
sha = sha256()
sha.update(SourceID_Str.encode())
return sha.hexdigest()[:8] # 取前八位
class Index: class Index:
def __init__(self,indexurl): def __init__(self,indexurl):
self.packageList = {} self.packageList = {}
self.IndexURL = indexurl self.IndexURL = indexurl['url']
self.number = 0 self.number = 0
self.priority = indexurl['priority']
def addPackage(self, name): def addPackage(self, name):
self.packageList[name] = 'H' self.packageList[name] = '1'
self.number += 1 self.number += 1
def getIndex(url): def getIndex(url):
req = requests.get(url) # 请求HTML req = requests.get(url['url']) # 请求HTML
HTMLIndex = req.text HTMLIndex = req.text
ClassIndex = Index(url) ClassIndex = Index(url)
@ -60,8 +53,8 @@ def getAllIndex():
console.print('❌ [red]You have not configured any sources.[/red]') console.print('❌ [red]You have not configured any sources.[/red]')
exit(1) exit(1)
for url in SourceList: # 遍历源列表 for source in SourceList: # 遍历源列表
console.print('📚 Downloading index from', url+'...') console.print('📚 Downloading index from', source['url']+'...')
getIndex(url) getIndex(source)
console.print('✅ [green]Index downloaded successfully![/green]') console.print('✅ [green]Index downloaded successfully![/green]')

View File

@ -1,15 +1,19 @@
#pylint:disable=W0622 #pylint:disable=W0622
import os import os
from subprocess import Popen,PIPE from subprocess import Popen
import sys import sys
import pathlib import pathlib
import dill import dill
from rich import print from rich.console import Console
import time import time
import subprocess
from moyanlib import jsons
from platformdirs import PlatformDirs from platformdirs import PlatformDirs
dirs = PlatformDirs("PMPT", "MoYan") dirs = PlatformDirs("PMPT", "MoYan")
IndexList = [] IndexList = []
console = Console()
def getVer(baseVar): 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])
return baseVar return baseVar
@ -21,17 +25,26 @@ def init():
os.makedirs(dirs.user_config_dir,exist_ok=True) os.makedirs(dirs.user_config_dir,exist_ok=True)
os.makedirs(dirs.user_cache_dir,exist_ok=True) os.makedirs(dirs.user_cache_dir,exist_ok=True)
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']:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def loadIndex(): def loadIndex():
''' '''
加载索引 加载索引
''' '''
if len(IndexList) == 0: # 判断是否为空 sourceList = jsons.load(open(os.path.join(dirs.user_config_dir,'Source.json')))
print('🔍 Loading index...') sourceList = bubbleSort(sourceList)
IndexDir = pathlib.Path(os.path.join(dirs.user_data_dir,'Index')) for source in sourceList:
for i in IndexDir.iterdir(): # 遍历索引文件夹 if not os.path.exists(os.path.join(dirs.user_data_dir,'Index',source['id']+'.pidx')):
IndexFile = dill.load(open(i,'rb')) # 加载索引 console.print(f'⚠️ [yellow]{source["url"]} did not create an index.[/yellow]')
continue
IndexFile = dill.load(open(os.path.join(dirs.user_data_dir,'Index',source['id']+'.pidx'),'rb')) # 加载索引
IndexList.append(IndexFile) IndexList.append(IndexFile)
if len(IndexList) == 0: if len(IndexList) == 0:
raise FileNotFoundError('No index. Run "pmpt update" first to update the index') raise FileNotFoundError('No index. Run "pmpt update" first to update the index')
@ -46,9 +59,14 @@ def runpip(command,other=None,dbg=False) -> Popen:
Command = baseCommand + other Command = baseCommand + other
if dbg: if dbg:
print('Command to be run:',' '.join(Command)) console.print('Command to be run:',' '.join(Command))
runClass = Popen(Command) runClass = Popen(Command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
runClass.wait() for line in iter(runClass.stdout.readline, b''):
# 在这里你可以对每一行输出进行处理
line = line.decode('utf-8').strip() # 将字节转换为字符串并去除换行符
console.print(line)
runClass.communicate()
return runClass return runClass