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 util
from moyanlib import jsons
import os
from . import source as sou
from . import install as installs
from . import search as searchs
@click.group()
def cli():
try:
import pip
except ImportError:
util.console.print('❌ [red]pip module not found![/red]')
exit(1)
util.init() # 初始化
@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('--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)
@ -51,18 +58,26 @@ def source():
@source.command()
@click.argument('url')
def add(url):
sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json')))
if url in sourceList:
print('The source already exists')
exit()
sourceList.append(url)
jsons.dump(sourceList,open(os.path.join(util.dirs.user_config_dir,'Source.json')))
@click.option('--priority','-p',default=1,type=int)
def add(*args,**kwargs):
sou.add(*args,**kwargs)
@source.command(name='list')
def lists():
sourceList = jsons.load(open(os.path.join(util.dirs.user_config_dir,'Source.json')))
ids = 1
for i in sourceList:
print(str(ids)+'.',i)
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)
if __name__ == '__main__':
cli()

View File

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

View File

@ -3,9 +3,8 @@ from . import util
from moyanlib import jsons
from .install import search
import os
from rich.console import Console
console = Console()
console = util.console
def main(name,allinfo,api_url):
if not search(name):
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))
if req.status_code == 404:
console.print(404 )
console.print('❌ [red]The package does not exist[/red]')
exit()
elif req.status_code != 200:
@ -32,7 +32,8 @@ def main(name,allinfo,api_url):
print('Summary:',packageInfo['info']['summary'])
print('Keywords:',packageInfo['info']['keywords'])
print('License:',packageInfo['info']['license'])
print('Dependent Library:',', '.join(packageInfo['info']['requires_dist']))
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}')

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

View File

@ -1,15 +1,19 @@
#pylint:disable=W0622
import os
from subprocess import Popen,PIPE
from subprocess import Popen
import sys
import pathlib
import dill
from rich import print
from rich.console import Console
import time
import subprocess
from moyanlib import jsons
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])
return baseVar
@ -21,19 +25,28 @@ def init():
os.makedirs(dirs.user_config_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():
'''
加载索引
'''
if len(IndexList) == 0: # 判断是否为空
print('🔍 Loading index...')
IndexDir = pathlib.Path(os.path.join(dirs.user_data_dir,'Index'))
for i in IndexDir.iterdir(): # 遍历索引文件夹
IndexFile = dill.load(open(i,'rb')) # 加载索引
IndexList.append(IndexFile)
if len(IndexList) == 0:
raise FileNotFoundError('No index. Run "pmpt update" first to update the index')
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')):
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)
if len(IndexList) == 0:
raise FileNotFoundError('No index. Run "pmpt update" first to update the index')
def runpip(command,other=None,dbg=False) -> Popen:
'''
@ -46,9 +59,14 @@ def runpip(command,other=None,dbg=False) -> Popen:
Command = baseCommand + other
if dbg:
print('Command to be run:',' '.join(Command))
console.print('Command to be run:',' '.join(Command))
runClass = Popen(Command)
runClass.wait()
runClass = Popen(Command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for line in iter(runClass.stdout.readline, b''):
# 在这里你可以对每一行输出进行处理
line = line.decode('utf-8').strip() # 将字节转换为字符串并去除换行符
console.print(line)
runClass.communicate()
return runClass