Skip to content

Commit

Permalink
Add logging and try to collect errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhaopudark committed Oct 20, 2023
1 parent 180def0 commit 91d03a6
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 34 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
**__pycache__/
Logs/
Output/
38 changes: 38 additions & 0 deletions Utils/log_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import logging
import logging.handlers
def logger_factory(name:str,level:int=logging.INFO)->logging.Logger:
"""
Generate a logger with file and console handler.
Args:
name: the name of the logger and the indicator of the log file
level: the level of the logger
Returns:
logger: an instance of logging.Logger that has been configured
"""
logger = logging.getLogger(name)
logger.setLevel(level)
# check if the console handler exists
console_handler_exists = any(
isinstance(handler, logging.StreamHandler)
for handler in logger.handlers
)
file_handler_exists = any(
isinstance(handler, logging.FileHandler)
for handler in logger.handlers
)
file_handler = logging.handlers.RotatingFileHandler(
f"./Logs/{name}.log",
maxBytes=2*1024*1024,
backupCount=5,encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
if not file_handler_exists:
logger.addHandler(file_handler)
if not console_handler_exists:
logger.addHandler(console_handler)
logger.propagate = False
return logger
81 changes: 49 additions & 32 deletions auto_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,43 @@
# -*- coding: utf-8 -*-
import os
import sys
import logging
import pathlib
import subprocess
import json
from packaging import version

from Utils.github_helper import get_latest_stable_version
from Utils.log_helper import logger_factory

logger = logger_factory(name="auto_update",level=logging.DEBUG)

class UpdateException(Exception):
def __init__(self, message="Update Exception"):
self.message = message
super().__init__(self.message)
class BuildException(Exception):
def __init__(self, message="Build Exception"):
self.message = message
super().__init__(self.message)

def local_build_test(build_script_path:str,build_output_path:str):
print('Cleaning...')
if os.path.exists(build_output_path):
os.remove(build_output_path)
command = f'pwsh -ExecutionPolicy Bypass -File "{build_script_path}"'
print('Compiling...')
try:
logger.info('Cleaning...')
if os.path.exists(build_output_path):
os.remove(build_output_path)
command = f'pwsh -ExecutionPolicy Bypass -File "{build_script_path}"'
logger.info('Compiling...')
subprocess.run(command, shell=True, check=True)
print("PowerShell: Compiled successfully.")
if os.path.exists(build_output_path):
return True
logger.info("PowerShell: Build succeed.")
else:
return False
raise BuildException("Build failed.")
except subprocess.CalledProcessError as e:
print(f"PowerShell: Compiled failed. Error: {e}")
return False
raise BuildException(f"Build failed. Build script error: {e}")
except Exception as e:
print(f"Error: {e}")
return False
raise BuildException(f"Build failed. Error: {e}")


def main(json_info_path:str):
with open(json_info_path, 'r', encoding='utf-8') as json_file:
Expand All @@ -47,28 +59,33 @@ def main(json_info_path:str):
defalut_version=parsed_dict["nerd-fonts"]["defalut_version"]
)
if ((jbm_version_new > jbm_version_old) and (nf_version_new > nf_version_old)):

if local_build_test(
logger.info("Test build on local.")
local_build_test(
build_script_path=parsed_dict["self"]["build_script_path"],
build_output_path=parsed_dict["self"]["build_output_path"]):
self_version = version.parse(parsed_dict['self']['version'])
self_version = version.parse(f"v{self_version.major}.{self_version.minor+1}")
parsed_dict['self']['version'] = f"v{self_version}"
parsed_dict["JetBrainsMono"]["version"] = f"v{jbm_version_new}"
parsed_dict["nerd-fonts"]["version"] = f"v{nf_version_new}"
with open(json_info_path, 'w', encoding='utf-8') as json_file:
json.dump(parsed_dict, json_file)
print("Local build success. File updated.")
else:
print("Local build failed. Nothing changed.")
sys.exit(1) # return failed code (non-zero) to shell
build_output_path=parsed_dict["self"]["build_output_path"])
self_version = version.parse(parsed_dict['self']['version'])
self_version = version.parse(f"v{self_version.major}.{self_version.minor+1}")
parsed_dict['self']['version'] = f"v{self_version}"
parsed_dict["JetBrainsMono"]["version"] = f"v{jbm_version_new}"
parsed_dict["nerd-fonts"]["version"] = f"v{nf_version_new}"
with open(json_info_path, 'w', encoding='utf-8') as json_file:
json.dump(parsed_dict, json_file)
logger.info("File updated.")
else:
print("The object is the latest version and there is no need to compile and upload it.")



raise UpdateException("The object is the latest version and there is no need to compile and upload it.")

if __name__ == "__main__":
script_root = pathlib.Path(__file__).parent.absolute()
main(json_info_path=f"{script_root}/basicinfo.json")
try:
script_root = pathlib.Path(__file__).parent.absolute()
main(json_info_path=f"{script_root}/basicinfo.json")
except BuildException as e:
logger.error(f"Build Exception: {e}")
sys.exit(1)
except UpdateException as e:
logger.error(f"Update Exception: {e}")
sys.exit(2)
except Exception as e:
logger.error(f"Other Exception: {e}")
sys.exit(3)


2 changes: 1 addition & 1 deletion basicinfo.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"self": {"build_script_path": "./build.ps1", "build_output_path": "./Output/JetBrainsMonoNerdFont-Regular.ttf", "version": "v1.1", "defalut_version": "v0.0"}, "JetBrainsMono": {"version": "v2.304", "user_name": "JetBrains", "repo_name": "JetBrainsMono", "defalut_version": "v0.0"}, "nerd-fonts": {"version": "v3.0.2", "user_name": "ryanoasis", "repo_name": "nerd-fonts", "defalut_version": "v0.0.0"}}
{"self": {"build_script_path": "./build.ps1", "build_output_path": "./Output/JetBrainsMonoNerdFont-Regular.ttf", "version": "v1.2", "defalut_version": "v0.0"}, "JetBrainsMono": {"version": "v2.304", "user_name": "JetBrains", "repo_name": "JetBrainsMono", "defalut_version": "v0.0"}, "nerd-fonts": {"version": "v3.0.2", "user_name": "ryanoasis", "repo_name": "nerd-fonts", "defalut_version": "v0.0.0"}}
2 changes: 1 addition & 1 deletion build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ $temp_path = "${Home}/tmp/$guid"
$font_to_be_pathced = "JetBrainsMono-Regular.ttf"
$font_patched = "JetBrainsMonoNerdFont-Regular.ttf"
New-Item $temp_path -ItemType Directory -Force

New-Item "./Output" -ItemType Directory -Force
## Build JetBrainsMono
git submodule update --init --recursive # check the submodule `JetBrainsMono` as latest release version
git submodule foreach 'git reset --hard && git checkout master && git pull' # should be master instead of main
Expand Down

0 comments on commit 91d03a6

Please sign in to comment.