Skip to content

Commit

Permalink
using kwargs in script
Browse files Browse the repository at this point in the history
  • Loading branch information
Light-Beacon committed Apr 26, 2024
1 parent 875ec99 commit 098e830
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 50 deletions.
24 changes: 17 additions & 7 deletions Core/Code_Formatter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from typing import Any, Callable, Dict
from .Debug import LogWarning, LogDebug

def format_code(code:str,card,resources,children_code,stack:list = []):

def format_code(code:str,card:Dict[str,object],
project,children_code:str='',stack:list = []):
'''格式化代码'''
matches = findall_placeholders(code)
for match in matches:
Expand All @@ -12,9 +14,13 @@ def format_code(code:str,card,resources,children_code,stack:list = []):
LogWarning(f'[Formatter] 检测到循环调用: {stack}')
return code
for item in qurey_tuple[1:]:
item = format_code(item,card,resources,children_code,stack)
# 格式化参数
item = format_code(code=item,card=card,project=project,
children_code=children_code,stack=stack)
if attr_name.startswith('$') or attr_name.startswith('@'):
replacement = runScript(qurey_tuple[0][1:],resources,card,qurey_tuple,children_code)
replacement = runScript(script_name=qurey_tuple[0][1:],
project=project,card=card,args=qurey_tuple[1:],
children_code=children_code)
elif attr_name in card:
replacement = str(card[attr_name])
else:
Expand All @@ -25,24 +31,26 @@ def format_code(code:str,card,resources,children_code,stack:list = []):
continue
stack.append(attr_name)
try:
replacement = format_code(replacement,card,resources,children_code,stack)
replacement = format_code(replacement,card,project,children_code,stack)
finally:
stack.pop()
code = code.replace(f'${{{match}}}',replacement,1)
return code

script: Callable[[Dict,Any], str]
def runScript(script_name:str,resources,card,args,children_code):
def runScript(script_name:str,project,card:Dict[str,object],
args:list,children_code:str):
'''获取脚本输出结果'''
resources = project.resources
scripts = resources.scripts
if script_name == 'ChildrenPresenter':
return children_code
script_code = scripts.get(script_name)
if script_code is None:
LogWarning(f'[Formatter] 尝试调用不存在的脚本: {script_name}')
return ''
result = scripts[script_name](card,args,resources)
result = format_code(result,card,resources,children_code)
result = scripts[script_name](*args,card=card,res=resources,proj=project)
result = format_code(result,card,project,children_code)
return result

def split_args(string:str):
Expand Down Expand Up @@ -72,6 +80,8 @@ def split_args(string:str):
return args

def findall_placeholders(string:str):
if string == None:
return []
placeholders = []
pare_deepth = 0
sp_mode = False
Expand Down
35 changes: 22 additions & 13 deletions Core/Library.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from .FileIO import ScanDire,ScanSubDire
from .Debug import LogInfo,LogError
from .Code_Formatter import format_code
import os

class Library:
Expand All @@ -14,16 +13,8 @@ def __init__(self,data:dict):
self.sub_libraries = {} # 子库
self.cards = {}
self.location = os.path.dirname(data['file_path'])
for pair in ScanDire(self.location,r'^(?!^__LIBRARY__.yml$).*$'): # 库所拥有的卡片
data, filename, exten = pair
name = filename
if isinstance(data,dict):
if 'name' in data:
name = data['name']
self.cards[name] = data
else:
self.cards[name] = { 'data':data }
self.cards[name].update({'data':data,'file_name':filename,'file_exten':exten})
for file_tuple in ScanDire(self.location,r'^(?!^__LIBRARY__.yml$).*$'): # 库所拥有的卡片
self.add_card_from_file_tuple(file_tuple)
self.add_sub_libraries(ScanSubDire(self.location,'__LIBRARY__.yml')) # 遍历添加子库

@classmethod
Expand All @@ -37,7 +28,7 @@ def decorateCard(cls,card,fill,cover):
card.update(cover)
cloned_fill.update(card)
return cloned_fill

def __decorateCard(self,card):
'''用本卡片库的 fill 和 cover 修饰卡片'''
return self.decorateCard(card,self.fill,self.cover)
Expand Down Expand Up @@ -80,6 +71,17 @@ def getCardFromLibMapping(self,lib_name,card_ref,is_original):
else:
raise KeyError(LogError(f'[Library] Cannot find library "{card_ref}"'))

def add_card_from_file_tuple(self,file_info_tuple):
data, filename, exten = file_info_tuple
name = filename
if isinstance(data,dict):
if 'name' in data:
name = data['name']
self.cards[name] = data
else:
self.cards[name] = {'data':data }
self.cards[name].update({'data':data,'file_name':filename,'file_exten':exten})

def add_sub_libraries(self,yamldata):
'''增加子库'''
def add_sub_library(self,yamldata):
Expand All @@ -103,4 +105,11 @@ def add_sub_library(self,yamldata):
add_sub_library(self,yamldata[0])
else:
add_sub_library(self,yamldata)
# DEV NOTICE 如果映射的内存占用太大了就将每一个卡片和每一个子库的路径压成栈,交给根库来管理
# DEV NOTICE 如果映射的内存占用太大了就将每一个卡片和每一个子库的路径压成栈,交给根库来管理

def get_all_cards(self):
print(self.name)
result = [self.__decorateCard(card) for card in self.cards.values()]
for lib in self.sub_libraries.values():
result += [self.__decorateCard(card) for card in lib.get_all_cards()]
return result
9 changes: 6 additions & 3 deletions Core/Project.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ def import_pack(self,path):
LogInfo(f'[Project] Loading pages')
for page in ScanDire(f'{self.base_path}{sep}Pages',r'.*'):
self.import_page(page)


def getAllCard(self):
return self.base_library.get_all_cards()

def __init__(self,path):
LogInfo(f'[Project] Initing ...')
envpath = os.path.dirname(os.path.dirname(__file__))
Expand All @@ -41,7 +44,7 @@ def __init__(self,path):
self.load_plugins(f'{envpath}{sep}Plugin')
self.pages = {}
self.import_pack(path)
self.TemplateManager = TemplateManager(self.resources)
self.TemplateManager = TemplateManager(self)
LogInfo(f'[Project] Pack loaded successful!')

def import_page(self,page_tuple):
Expand All @@ -60,7 +63,7 @@ def import_page(self,page_tuple):
LogWarning(f'[Project] Page file not supported: {file_name}.{file_exten}')

def get_card_xaml(self,card_ref):
card_ref = format_code(card_ref,{},self.resources,'')
card_ref = format_code(code=card_ref,card={},project=self)
if ';' in card_ref:
code = ''
for each_card_ref in card_ref.split(';'):
Expand Down
19 changes: 10 additions & 9 deletions Core/Templates_Manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ def filter_match(template,card):
return True

class TemplateManager:
def __init__(self,resources: Resource):
self.resources = resources
self.templates = resources.templates
def __init__(self,project):
self.project = project
self.resources = project.resources
self.templates = self.resources.templates

def expend_card_placeholders(self,card:dict,children_code):
q = Queue()
Expand All @@ -60,7 +61,7 @@ def expend_card_placeholders(self,card:dict,children_code):
break
key = q.get()
try:
card[key] = format_code(str(card[key]),card,self.resources,children_code)
card[key] = format_code(str(card[key]),card,self.project,children_code)
tries = 0
except KeyError:
q.put(key)
Expand All @@ -77,13 +78,13 @@ def build_with_template(self,card,template_name,children_code) -> str:
code = ''
card = self.expend_card_placeholders(card,children_code)
for cpn in target_template['components']:
cpn = format_code(cpn,card,self.resources,'')
cpn = format_code(cpn,card,self.project,'')
if cpn in self.resources.components:
code += format_code(code = self.resources.components[cpn],card = card,
resources=self.resources,children_code = children_code)
code += format_code(code = self.resources.components[cpn], card = card,
project=self.project, children_code = children_code)
elif cpn.startswith('$') or cpn.startswith('@'):
args = cpn[1:].split('|')
code += runScript(args[0],self.resources,card,args,children_code)
code += runScript(args[0],self.project,card,args[1:],children_code)
else:
LogWarning(f'[TemplateManager] {template_name}模版中调用了未载入的构件{cpn},跳过')
if 'containers' in target_template:
Expand Down Expand Up @@ -111,7 +112,7 @@ def packin_containers(self,tree_path:Union[str,List[str]],card,code:str):
case _:
if container in self.resources.components:
current_code = format_code(self.resources.components[container],
card,self.resources,current_code)
card,self.project,current_code)
else:
raise ValueError('容器路径中存在不存在的组件')
return current_code
Expand Down
2 changes: 1 addition & 1 deletion Plugin/Markdown/Resources/Scripts/GetMdH1.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import markdown
import re
def script(card,args,res):
def script(card,**kwargs):
exten = card['file_exten']
if exten != 'md' and exten != 'markdown':
return 'NOT A MARKDOWN DOCUMENT!'
Expand Down
2 changes: 1 addition & 1 deletion Plugin/Markdown/Resources/Scripts/MarkdownPresenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,5 +129,5 @@ def convert(card,res):
xaml = html2xaml(html,res)
return xaml

def script(card,args,res):
def script(card,res,**kwargs):
return convert(card,res)
39 changes: 24 additions & 15 deletions Resources/Scripts/IF.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
from Core.Code_Formatter import format_code
def script(eq_expression:str,true_return,false_return='',**kwargs):
card = kwargs['card']
eq_expression.replace(' ','')
return true_return if iseq(eq_expression,card) else false_return

def script(card,args,res):
args[1].replace(' ','')
if '=' in args[1]:
eqs = args[1].split('=',1)
if eqs[0] in card and card[eqs[0]] == eqs[1]:
return args[2]
def iseq(eq_expression,card) -> bool:
if '=' in eq_expression:
eqexp_left, eqexp_right = eq_expression.split('=',1)
eqexp_left = format_eq(eqexp_left,card)
eqexp_right = format_eq(eqexp_right,card)
if eqexp_left == eqexp_right:
return True
else:
if args[1].startswith('!'):
if args[1][1:] not in card or args[1][1:].lower() in ['false','null']:
return args[2]
if args[1] in card and args[1].lower() not in ['false','null']:
return args[2]
if len(args) > 3:
return args[3]
return ''
if eq_expression.startswith('!'):
if format_eq(eq_expression[1:],card) in ['false','null','none', None]:
return True
else:
if format_eq(eq_expression,card) not in ['false','null','none', None]:
return True
return False

def format_eq(expression:str,card):
if(expression.startswith('$')):
return card.get(expression[1:])
else:
return expression
3 changes: 2 additions & 1 deletion Resources/Scripts/RawPresenter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
def script(card,args,res):
def script(**kwargs):
card = kwargs['card']
if 'data' in card:
return card['data']
else:
Expand Down

0 comments on commit 098e830

Please sign in to comment.