Skip to content

Commit

Permalink
Merge pull request #86 from iewnfod/nightly
Browse files Browse the repository at this point in the history
Update to Stable
  • Loading branch information
lightumcc authored Apr 6, 2024
2 parents 9dd035a + e1bf2ff commit b9d2a6b
Show file tree
Hide file tree
Showing 17 changed files with 23,992 additions and 23,315 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ It runs the entire file if `filepath` is provided, otherwise, it enters playgrou
| `-h` | `--help` | To show the help page |
| `-k` | `--keywords` | To show all the keywords |
| `-m` | `--migrate` | To migrate `.p` files to `.cpc` in a specified directory |
| `-n` | `--notification` | To show notification published by developer (only if this is not expired) |
| `-p` | `--parse` | To show parse information during running |
| `-t` | `--time` | To show the time for the script to run |
| `-u` | `--update` | To update the version |
Expand Down Expand Up @@ -108,6 +109,15 @@ It runs the entire file if `filepath` is provided, otherwise, it enters playgrou
- `recursion-limit(rl)`
all integer number as the recursion depth limit of the interpreter.

- `integrity-protection`

- `true`: Enable integrity protection.
- `false`: Disable integrity protection.

> Integrity Protection prevent any accidental or malicious modification of the interpreter.
> This protection will be automatically disabled in developer mode.
- `dev`

- `true`: Enable developer mode.
Expand Down
10 changes: 10 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ cpc [file_paths] [options]
| `-h` | `--help` | 显示帮助页面 |
| `-k` | `--keywords` | 显示所有的关键字 |
| `-m` | `--migrate` | 将一个目录中的所有 `.p` 文件切换为 `.cpc` |
| `-n` | `--notification` | 显示由开发者发布的未过期通知 |
| `-p` | `--parse` | 显示所有解析的信息 |
| `-t` | `--time` | 显示运行脚本花费的时间 |
| `-u` | `--update` | 更新此解释器的版本 |
Expand Down Expand Up @@ -100,6 +101,15 @@ cpc [file_paths] [options]
- `true`: 启用开发者模式。
- `false`: 关闭开发者模式。

- `integrity-protection`

- `true`: 启用完整性保护。
- `false`: 禁用完整性保护。

> 完整性保护将会阻止任何意外或恶意的解释器修改。
> 此保护将在开发者模式下被自动禁用。
- 开发者选项

- `dev.simulate-update`
Expand Down
4 changes: 4 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from src.line_commands import run_command
from src.update import update
from src.update import update_expired
from src.update import integrity_protection

import sys
import os
Expand Down Expand Up @@ -193,6 +194,9 @@ def main(input_=None, output_=None, addition_file_name=None):
if addition_file_name:
file_paths.add(addition_file_name)

if not config.get_config('dev') and config.get_config('integrity-protection'):
integrity_protection()

#自动更新
if config.get_config('dev.simulate-update') or (config.get_config('auto-update') and not config.get_config('dev') and update_expired()):
update()
Expand Down
9 changes: 9 additions & 0 deletions notification/notification.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"type": "deprecate",
"branch": ["stable", "nightly", "dev"],
"expiry_date": "2024-04-05",
"deprecation": {
"keyword": ["Ucase", "Lcase"],
"deprecation_date": "2024-03-29"
}
}
10 changes: 10 additions & 0 deletions notification/template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"type": "add|update|deprecate",
"branch": ["stable", "nightly", "dev"],
"expiry_date": "YYYY-MM-DD",
"content": "Update Content",
"deprecation": {
"keyword": ["Deprecated Keyword 1", "Deprecated Keyword 2"],
"deprecation_date": "YYYY-MM-DD"
}
}
46,822 changes: 23,678 additions & 23,144 deletions parser.out

Large diffs are not rendered by default.

287 changes: 146 additions & 141 deletions parsetab.py

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pkg-script/postupgrade.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ git config --global --add safe.directory /usr/local/sbin/CAIE_Code || exit 1
chown -R $loggedInUser $current_dir || exit 1

# 链接到 bin 目录
mkdir -p /usr/local/bin
ln -sf ${current_dir}/bin/cpc /usr/local/bin/cpc || exit 1

# 链接到 man 目录,如果失败则返回退出代码1
Expand Down
22 changes: 0 additions & 22 deletions scripts/string.cpc
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,6 @@ FUNCTION Split(s : STRING, sep : STRING) RETURNS ARRAY
RETURN returnArr
ENDFUNCTION

FUNCTION Lcase(s : STRING) RETURNS STRING
DECLARE result : STRING
result <- ""

FOR i <- 1 TO LENGTH(s)
result <- result & LCASE(CHAR(MID(s, i, 1)))
NEXT i

RETURN result
ENDFUNCTION

FUNCTION Ucase(s : STRING) RETURNS STRING
DECLARE result : STRING
result <- ""

FOR i <- 1 TO LENGTH(s)
result <- result & UCASE(CHAR(MID(s, i, 1)))
NEXT i

RETURN result
ENDFUNCTION

FUNCTION TrimStart(s : STRING) RETURNS STRING
DECLARE len : INTEGER
len <- LENGTH(s)
Expand Down
13 changes: 9 additions & 4 deletions src/AST/calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ def get_tree(self, level=0):
def exe(self):
n1 = self.left.exe()
n2 = self.right.exe()
if any(i[1] == 'STRING' for i in [n1, n2]):
add_error_message(f'Cannot multiply `{n1[1]}` with `{n2[1]}`', self)
return
try:
v = n1[0] * n2[0]
if int(v) == v:
Expand Down Expand Up @@ -108,12 +111,14 @@ def get_tree(self, level=0):
def exe(self):
s1 = self.left.exe()
s2 = self.right.exe()
try:
return (s1[0] + s2[0], 'STRING')
except:
if all(i[1] in ('STRING', 'CHAR') for i in [s1, s2]):
try:
return (s1[0] + s2[0], 'STRING')
except:
add_error_message(f'Cannot connect `{s1[1]}` with `{s2[1]}`', self)
else:
add_error_message(f'Cannot connect `{s1[1]}` with `{s2[1]}`', self)


class Op_mod(AST_Node):
def __init__(self, left, right, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand Down
34 changes: 34 additions & 0 deletions src/AST/var.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,37 @@ def exe(self):
add_error_message(f'Cannot assign `{assign_item}` to `{target_item}`', self)
else:
add_error_message(f'Target item does not exist', self)

class Ids(AST_Node):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.type = 'IDS'
self.ids = []

def get_tree(self, level=0):
r = LEVEL_STR * level + self.type
for i in self.ids:
r += '\n' + LEVEL_STR * (level + 1) + i
return r

def add_id(self, id):
self.ids.append(id)

def exe(self):
return self.ids

class MultiVariables(AST_Node):
def __init__(self, ids, var_type, private=False, *args, **kwargs):
super().__init__(*args, **kwargs)
self.type = 'MULTI_VARIABLES'
self.ids = ids
self.var_type = var_type
self.private = private

def get_tree(self, level=0):
return LEVEL_STR * level + self.type + "\n" + self.ids.get_tree(level+1) + "\n" + LEVEL_STR * (level+1) + str(self.var_type)

def exe(self):
id_list = self.ids.exe()
for id in id_list:
Variable(id, self.var_type, self.private).exe()
1 change: 1 addition & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def __init__(self, config_file_name=".cpc_config.json"):
self.config = {
'remote': _Config('remote', 'https://github.com/iewnfod/CAIE_Code.git', remote_update),
'dev': _Config('dev', False, dev_mod),
'integrity-protection': _Config('integrity-protection', True, integrity_protection),
'branch': _Config('branch', 'stable', branch_update),
'rl': _Config('recursion-limit', 1000, recursive_limit),
'dev.simulate-update': _Config('dev.simulate-update', False, simulate_update),
Expand Down
2 changes: 2 additions & 0 deletions src/config_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ def update(self, obj, val):

dev_mod = DictConfig({'true': True, 'false': False})

integrity_protection = DictConfig({'true': True, 'false': False})

branch_update = SetConfig({'stable', 'nightly', 'dev'})

simulate_update = DictConfig({'true': True, 'false': False})
Expand Down
9 changes: 7 additions & 2 deletions src/options.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import platform
from .update import VERSION, update, get_commit_hash_msg, get_current_branch
from .update import VERSION, update, get_commit_hash_msg, get_current_branch, show_notification
import os

PLATFORM = f'[ {platform.python_implementation()} {platform.python_version()} ] on {platform.system()}'
Expand All @@ -22,10 +22,11 @@ def get_value(value):
return options_dict[value]

def standard_output():
import datetime
print(f'CAIE Pseudocode Interpreter v{VERSION} ({get_current_branch()}/{get_commit_hash_msg()[0]})')
print(f'Using {PLATFORM}')
print('Repository at \033[4mhttps://github.com/iewnfod/CAIE_Code/\33[0m')
print('Copyright (c) 2023 Iewnfod. ')
print(f'Copyright © {datetime.datetime.now().year} Iewnfod. ')
print('All Rights Reserved. ')

def open_parse_info():
Expand Down Expand Up @@ -87,6 +88,9 @@ def show_keywords():
def remove_error():
options_dict['show_error'] = False

def notification():
show_notification(get_current_branch())

def update_version():
update()

Expand Down Expand Up @@ -178,6 +182,7 @@ def __lt__(self, other):
Opt('-t', '--time', get_time, 'To show the time for the script to run', False),
Opt('-k', '--keywords', show_keywords, 'To show all the keywords', True),
Opt('-ne', '--no-error', remove_error, 'To remove all error messages', False),
Opt('-n', '--notification', notification, 'To show notification published by developer (only if this is not expired)', True),
Opt('-u', '--update', update_version, 'To check or update the version (only if this is installed with git)', True),
Opt('-c', '--config', change_config, 'To set configs of this interpreter', True, 2),
Opt('-m', '--migrate', migrate_files, 'To migrate .p files to .cpc in a specified directory', True, 1),
Expand Down
19 changes: 19 additions & 0 deletions src/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,29 @@ def p_declare_statement(p):
| PUBLIC ID COLON ID"""
p[0] = AST.Variable(p[2], p[4], p=p)

def p_multi_declare_statement(p):
"""statement : DECLARE ids COLON ID
| PUBLIC ids COLON ID"""
p[0] = AST.MultiVariables(p[2], p[4], p=p)

def p_multi_id_expression(p):
"""ids : ids COMMA ID
| ID"""
if len(p) == 2:
p[0] = AST.Ids(p=p)
p[0].add_id(p[1])
else:
p[1].add_id(p[3])
p[0] = p[1]

def p_private_declare_statement(p):
"""statement : PRIVATE ID COLON ID"""
p[0] = AST.Variable(p[2], p[4], private=True, p=p)

def p_private_multi_declare_statement(p):
"""statement : PRIVATE ids COLON ID"""
p[0] = AST.MultiVariables(p[2], p[4], private=True, p=p)

def p_const_declare_statement(p):
"""statement : CONSTANT ID EQUAL expression
| CONSTANT ID ASSIGN expression"""
Expand Down
4 changes: 2 additions & 2 deletions src/requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ def test_requirements():
except:
print(f'Missing Important Dependence `{package_name}`\nTrying to Install for You...')
if os.environ.get('CODESPACES'):
os.system(f'{sys.executable} -m pip install {package_name}')
os.system(f'"{sys.executable}" -m pip install {package_name}')
else:
os.system(f'{sys.executable} -m pip install {package_name} -i {tuna}')
os.system(f'"{sys.executable}" -m pip install {package_name} -i {tuna}')
50 changes: 50 additions & 0 deletions src/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import os
import git
import requests
import json
from time import time
from datetime import datetime

VERSION = ''

Expand Down Expand Up @@ -46,6 +48,7 @@ def check_update(repo: git.Repo, remote: git.Remote):
elif local_commit_time > remote_commit_time:
print(f"Good! Good! You are faster than \033[1m{get_current_branch()}\033[0m branch!")
print("At", *get_commit_hash_msg())
show_notification(get_current_branch())
global super_fast
super_fast = True
return False
Expand All @@ -61,8 +64,10 @@ def _update(remote, repo):
repo.git.checkout(branch)
remote.pull()
print('\033[1mUpdate Successful\033[0m')
show_notification(get_current_branch())
else:
print('\033[1mSimulate Update Successful\033[0m')
show_notification(get_current_branch())
except:
print('\033[31;1mFailed to Update\033[0m')

Expand All @@ -87,6 +92,50 @@ def get_commit_hash_msg():
local_commit_message = repo.head.reference.commit.message.strip()
return latest_commit_hash, latest_commit_message, local_commit_hash, local_commit_message

def show_notification(_branch):
f = os.path.join(HOME_PATH, 'notification', 'notification.json')
with open(f, 'r') as file:
notification_data = json.load(file)
if _branch in notification_data['branch']:
expiry_date_str = notification_data['expiry_date']
current_time = datetime.now()
expiry_date = datetime.strptime(expiry_date_str, '%Y-%m-%d')
if current_time < expiry_date:
if notification_data['type'] == 'deprecate':
print(f"\033[1m❗DEPRECATED NOTIFICATION❗\33[1m")
deprecate_keyword = ', '.join(notification_data['deprecation']['keyword'])
deprecation_date_str = notification_data['deprecation']['deprecation_date']
deprecation_date = datetime.strptime(deprecation_date_str, '%Y-%m-%d')
if current_time > deprecation_date:
print(f"👉{deprecate_keyword}👈 has become deprecated since {notification_data['deprecation']['deprecation_date']}")
else:
print(f"👉{deprecate_keyword}👈 will be deprecated at {notification_data['deprecation']['deprecation_date']}")
elif notification_data['type'] == 'update':
print(f"\033[1m🎉UPDATE NOTIFICATION🎉\33[1m")
print(f"👉{notification_data['content']}")
elif notification_data['type'] == 'add':
print(f"\033[1m🎉NEW FEATURE NOTIFICATION🎉\33[1m")
print(f"👉{notification_data['content']}")
else:
print("🙁No developer notification available.")
else:
print("🙁No developer notification available.")

def integrity_protection():
repo = git.Repo(HOME_PATH)
if not os.environ.get('CODESPACES'):
current_branch = get_current_branch()
local_commit = repo.head.commit
remote_branch = repo.remote().refs[current_branch]
remote_commit = remote_branch.commit
diff = local_commit.diff(remote_commit)

if diff or repo.is_dirty():
repo.git.reset('--hard', remote_commit)
print("❗INTEGRITY WARNING❗")
print("Changes have been discarded")
print("---------------------------------")

def update():
from .global_var import config
if os.getenv('CODESPACES'):
Expand Down Expand Up @@ -121,3 +170,4 @@ def update():
else:
if not super_fast:
print(f'Good! You are using the latest \033[1m{get_current_branch()}\033[0m version!\nAt {local_commit_hash}: {local_commit_message}')
show_notification(get_current_branch())

0 comments on commit b9d2a6b

Please sign in to comment.