Compare commits

...

2 Commits

@ -7,7 +7,7 @@ import logging
import re
import sys
from lib.core.settings import IS_WIN
from lib.core.settings import IS_WIN # 导入一个设置用于判断是否在Windows系统上运行
if IS_WIN:
import ctypes
@ -16,14 +16,15 @@ if IS_WIN:
# Reference: https://gist.github.com/vsajip/758430
# https://github.com/ipython/ipython/issues/4252
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms686047%28v=vs.85%29.aspx
# 设置Windows API函数SetConsoleTextAttribute的参数和返回值类型
ctypes.windll.kernel32.SetConsoleTextAttribute.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.WORD]
ctypes.windll.kernel32.SetConsoleTextAttribute.restype = ctypes.wintypes.BOOL
def stdoutEncode(data): # Cross-referenced function
def stdoutEncode(data): # 用于编码标准输出数据的函数
return data
class ColorizingStreamHandler(logging.StreamHandler):
# color names to indices
# 定义颜色名称到索引的映射
color_map = {
'black': 0,
'red': 1,
@ -35,7 +36,7 @@ class ColorizingStreamHandler(logging.StreamHandler):
'white': 7,
}
# levels to (background, foreground, bold/intense)
# 定义日志级别到颜色和样式的映射
level_map = {
logging.DEBUG: (None, 'blue', False),
logging.INFO: (None, 'green', False),
@ -43,17 +44,19 @@ class ColorizingStreamHandler(logging.StreamHandler):
logging.ERROR: (None, 'red', False),
logging.CRITICAL: ('red', 'white', False)
}
csi = '\x1b['
reset = '\x1b[0m'
bold = "\x1b[1m"
disable_coloring = False
csi = '\x1b[' # ANSI转义序列的前缀
reset = '\x1b[0m' # ANSI重置颜色的转义序列
bold = "\x1b[1m" # ANSI加粗的转义序列
disable_coloring = False # 是否禁用颜色
@property
def is_tty(self):
# 检查流是否是终端
isatty = getattr(self.stream, 'isatty', None)
return isatty and isatty() and not self.disable_coloring
def emit(self, record):
# 发送日志记录
try:
message = stdoutEncode(self.format(record))
stream = self.stream
@ -76,9 +79,11 @@ class ColorizingStreamHandler(logging.StreamHandler):
if not IS_WIN:
def output_colorized(self, message):
# 如果不是Windows系统直接写入消息
self.stream.write(message)
else:
ansi_esc = re.compile(r'\x1b\[((?:\d+)(?:;(?:\d+))*)m')
# 正则表达式用于匹配ANSI转义序列
nt_color_map = {
0: 0x00, # black
@ -92,6 +97,7 @@ class ColorizingStreamHandler(logging.StreamHandler):
}
def output_colorized(self, message):
# 如果是Windows系统解析ANSI转义序列并设置控制台颜色
parts = self.ansi_esc.split(message)
h = None
fd = getattr(self.stream, 'fileno', None)
@ -131,9 +137,10 @@ class ColorizingStreamHandler(logging.StreamHandler):
ctypes.windll.kernel32.SetConsoleTextAttribute(h, color)
def _reset(self, message):
# 如果消息不以重置序列结尾,则添加重置序列
if not message.endswith(self.reset):
reset = self.reset
elif self.bold in message: # bold
elif self.bold in message: # 如果消息包含加粗,则在重置后加粗
reset = self.reset + self.bold
else:
reset = self.reset
@ -141,6 +148,7 @@ class ColorizingStreamHandler(logging.StreamHandler):
return reset
def colorize(self, message, levelno):
# 根据日志级别给消息上色
if levelno in self.level_map and self.is_tty:
bg, fg, bold = self.level_map[levelno]
params = []
@ -167,5 +175,6 @@ class ColorizingStreamHandler(logging.StreamHandler):
return message
def format(self, record):
# 格式化日志记录
message = logging.StreamHandler.format(self, record)
return self.colorize(message, record.levelno)

@ -64,14 +64,16 @@ class Magic:
return magic_file(self.cookie, filename)
def __del__(self):
# during shutdown magic_close may have been cleared already
# 析构函数,确保在对象被垃圾回收时关闭 libmagic cookie
if self.cookie and magic_close:
magic_close(self.cookie)
self.cookie = None
# 全局变量用于保存默认和MIME magic对象
_magic_mime = None
_magic = None
# 获取默认和MIME magic对象的函数
def _get_magic_mime():
global _magic_mime
if not _magic_mime:
@ -90,6 +92,7 @@ def _get_magic_type(mime):
else:
return _get_magic()
# 公共函数,用于识别文件和缓冲区
def from_file(filename, mime=False):
m = _get_magic_type(mime)
return m.from_file(filename)
@ -98,6 +101,7 @@ def from_buffer(buffer, mime=False):
m = _get_magic_type(mime)
return m.from_buffer(buffer)
# 使用 ctypes 导入 libmagic 库
try:
libmagic = None
@ -106,7 +110,7 @@ try:
from ctypes import c_char_p, c_int, c_size_t, c_void_p
# Let's try to find magic or magic1
# 尝试找到 libmagic 库
dll = ctypes.util.find_library('magic') or ctypes.util.find_library('magic1')
# This is necessary because find_library returns None if it doesn't find the library
@ -116,6 +120,7 @@ try:
except WindowsError:
pass
# 如果没有找到,尝试平台特定的路径
if not libmagic or not libmagic._name:
platform_to_lib = {'darwin': ['/opt/local/lib/libmagic.dylib',
'/usr/local/lib/libmagic.dylib',
@ -127,10 +132,12 @@ try:
except OSError:
pass
# 如果仍然没有找到,抛出 ImportError
if not libmagic or not libmagic._name:
# It is better to raise an ImportError since we are importing magic module
raise ImportError('failed to find libmagic. Check your installation')
# 定义 magic_t 类型和错误检查函数
magic_t = ctypes.c_void_p
def errorcheck(result, func, args):
@ -145,6 +152,7 @@ try:
return None
return filename.encode(sys.getfilesystemencoding())
# 使用 ctypes 定义 libmagic 函数
magic_open = libmagic.magic_open
magic_open.restype = magic_t
magic_open.argtypes = [c_int]
@ -198,28 +206,31 @@ try:
magic_compile.restype = c_int
magic_compile.argtypes = [magic_t, c_char_p]
# 如果 libmagic 无法导入,定义回退函数
except (ImportError, OSError):
from_file = from_buffer = lambda *args, **kwargs: MAGIC_UNKNOWN_FILETYPE
MAGIC_NONE = 0x000000 # No flags
MAGIC_DEBUG = 0x000001 # Turn on debugging
MAGIC_SYMLINK = 0x000002 # Follow symlinks
MAGIC_COMPRESS = 0x000004 # Check inside compressed files
MAGIC_DEVICES = 0x000008 # Look at the contents of devices
MAGIC_MIME = 0x000010 # Return a mime string
MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding
MAGIC_CONTINUE = 0x000020 # Return all matches
MAGIC_CHECK = 0x000040 # Print warnings to stderr
MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit
MAGIC_RAW = 0x000100 # Don't translate unprintable chars
MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors
MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files
MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files
MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries
MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type
MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details
MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files
MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff
MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran
MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens
# 定义 libmagic 标志常量
MAGIC_NONE = 0x000000 # 无标志
MAGIC_DEBUG = 0x000001 # 打开调试
MAGIC_SYMLINK = 0x000002 # 跟随符号链接
MAGIC_COMPRESS = 0x000004 # 检查压缩文件内部
MAGIC_DEVICES = 0x000008 # 查看设备内容
MAGIC_MIME = 0x000010 # 返回 MIME 字符串
MAGIC_MIME_ENCODING = 0x000400 # 返回 MIME 编码
MAGIC_CONTINUE = 0x000020 # 返回所有匹配项
MAGIC_CHECK = 0x000040 # 打印警告到标准错误
MAGIC_PRESERVE_ATIME = 0x000080 # 退出时恢复访问时间
MAGIC_RAW = 0x000100 # 不转换不可打印字符
MAGIC_ERROR = 0x000200 # 将 ENOENT 等视为真实错误
MAGIC_NO_CHECK_COMPRESS = 0x001000 # 不检查压缩文件
MAGIC_NO_CHECK_TAR = 0x002000 # 不检查 tar 文件
MAGIC_NO_CHECK_SOFT = 0x004000 # 不检查 magic 条目
MAGIC_NO_CHECK_APPTYPE = 0x008000 # 不检查应用程序类型
MAGIC_NO_CHECK_ELF = 0x010000 # 不检查 elf 详细信息
MAGIC_NO_CHECK_ASCII = 0x020000 # 不检查 ascii 文件
MAGIC_NO_CHECK_TROFF = 0x040000 # 不检查 ascii/troff
MAGIC_NO_CHECK_FORTRAN = 0x080000 # 不检查 ascii/fortran
MAGIC_NO_CHECK_TOKENS = 0x100000 # 不检查 ascii/tokens
MAGIC_UNKNOWN_FILETYPE = b"unknown"

Loading…
Cancel
Save