Skip to content

Commit

Permalink
refactor(lithium): 更新工具模块并优化C++代码风格
Browse files Browse the repository at this point in the history
- 重命名`byte_convertor`中的`format`参数为`data_format`,以提高清晰度。
- 在`cmake_generator`中,用`project_config`取代`config`变量名,增强可读性。
- 在`generator`中,通过添加文档字符串和改进命名规约,优化C++代码风格和可维护性。
- 在`html`模块中,添加和更新类的文档字符串,提供更清晰的API文档。
- 调整`package`模块的日志和错误处理,以提供更清晰的反馈。
- 在`src/atom/function/abi.hpp`中,优化`DemangleHelper`类的内部实现,避免潜在的溢出问题并提高效率。

BREAKING CHANGE: 函数参数的重命名可能会影响依赖于`byte_convertor`和`cmake_generator`模块的代码。请更新调用这些函数的代码,使用新的参数名称以确保兼容性。
  • Loading branch information
AstroAir committed Sep 18, 2024
1 parent c0eea67 commit 3c63b2b
Show file tree
Hide file tree
Showing 65 changed files with 3,713 additions and 2,040 deletions.
91 changes: 91 additions & 0 deletions modules/atom.sysinfo/component.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#include "atom/components/component.hpp"
#include <dlgs.h>
#include "atom/components/registry.hpp"

#include "atom/sysinfo/battery.hpp"
#include "atom/sysinfo/cpu.hpp"
#include "atom/sysinfo/disk.hpp"
#include "atom/sysinfo/gpu.hpp"
#include "atom/sysinfo/memory.hpp"
#include "atom/sysinfo/os.hpp"
#include "atom/sysinfo/wifi.hpp"

#include "atom/log/loguru.hpp"

using namespace atom::system;

ATOM_MODULE(atom_io, [](Component &component) {
DLOG_F(INFO, "Loading module {}", component.getName());

// ------------------------------------------------------------
// CPU
// ------------------------------------------------------------

component.def("cpu_usage", &getCurrentCpuUsage, "cpu",
"Get current CPU usage percentage");
component.def("cpu_temperature", &getCurrentCpuTemperature, "cpu",
"Get current CPU temperature");
component.def("cpu_model", &getCPUModel, "cpu", "Get CPU model name");
component.def("cpu_identifier", &getProcessorIdentifier, "cpu",
"Get CPU identifier");
component.def("cpu_frequency", &getProcessorFrequency, "cpu",
"Get current CPU frequency");
component.def("physical_packages", &getNumberOfPhysicalPackages, "cpu",
"Get number of physical CPU packages");
component.def("logical_cpus", &getNumberOfPhysicalCPUs, "cpu",
"Get number of logical CPUs");
component.def("cache_sizes", &getCacheSizes, "cpu", "Get CPU cache sizes");

// ------------------------------------------------------------
// Memory
// ------------------------------------------------------------

component.def("memory_usage", &getMemoryUsage, "memory",
"Get current memory usage percentage");
component.def("total_memory", &getTotalMemorySize, "memory",
"Get total memory size");
component.def("available_memory", &getAvailableMemorySize, "memory",
"Get available memory size");
component.def("physical_memory_info", &getPhysicalMemoryInfo, "memory",
"Get physical memory slot info");
component.def("virtual_memory_max", &getVirtualMemoryMax, "memory",
"Get virtual memory max size");
component.def("virtual_memory_used", &getVirtualMemoryUsed, "memory",
"Get virtual memory used size");
component.def("swap_memory_total", &getSwapMemoryTotal, "memory",
"Get swap memory total size");
component.def("swap_memory_used", &getSwapMemoryUsed, "memory",
"Get swap memory used size");
component.def("committed_memory", &getCommittedMemory, "memory",
"Get committed memory");
component.def("uncommitted_memory", &getUncommittedMemory, "memory",
"Get uncommitted memory");

component.defType<MemoryInfo>("memory_info");
component.defType<MemoryInfo::MemorySlot>("memory_slot");
component.def_v("memory_slot_type", &MemoryInfo::MemorySlot::type, "memory_slot",
"Get memory slot type");
component.def("memory_slot_capacity", &MemoryInfo::MemorySlot::capacity, "memory_slot",
"Get memory slot capacity");
component.def("memory_slot_clock_speed", &MemoryInfo::MemorySlot::clockSpeed, "memory_slot",
"Get memory slot clock speed");


// ------------------------------------------------------------
// Disk
// ------------------------------------------------------------

component.def("disk_usage", &getDiskUsage, "disk",
"Get current disk usage percentage");
component.def("is_hotspot_connected", &isHotspotConnected, "wifi",
"Check if the hotspot is connected");
component.def("wired_network", &getCurrentWiredNetwork, "wifi",
"Get current wired network");
component.def("wifi_name", &getCurrentWifi, "wifi",
"Get current wifi name");
component.def("current_ip", &getHostIPs, "network",
"Get current IP address");
component.def("gpu_info", &getGPUInfo, "gpu", "Get GPU info");

DLOG_F(INFO, "Loaded module {}", component.getName());
});
35 changes: 17 additions & 18 deletions modules/lithium.pytools/tools/byte_convertor.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def convert_file_to_array(
filename: str,
start: int = 0,
end: Optional[int] = None,
format: str = 'hex'
data_format: str = 'hex'
) -> str:
"""
Convert a binary file to a C-style array string.
Expand All @@ -105,22 +105,22 @@ def convert_file_to_array(
filename (str): Path to the binary file.
start (int): Start byte for conversion. Defaults to 0.
end (Optional[int]): End byte for conversion. Defaults to None (end of file).
format (str): Format of the array data ('hex', 'bin', 'dec'). Defaults to 'hex'.
data_format (str): Format of the array data ('hex', 'bin', 'dec'). Defaults to 'hex'.
Returns:
str: C-style array string.
"""
with open(filename, 'rb') as file:
data = file.read()[start:end]

if format == 'hex':
if data_format == 'hex':
return ', '.join(f'0x{b:02X}' for b in data)
elif format == 'bin':
elif data_format == 'bin':
return ', '.join(f'0b{b:08b}' for b in data)
elif format == 'dec':
elif data_format == 'dec':
return ', '.join(f'{b}' for b in data)
else:
raise ValueError(f"Unsupported format: {format}")
raise ValueError(f"Unsupported format: {data_format}")


def convert_array_to_file(
Expand Down Expand Up @@ -156,7 +156,7 @@ def extract_array_data_from_header(header_filename: str) -> str:
Raises:
ValueError: If no array data found in the header file.
"""
with open(header_filename, 'r') as file:
with open(header_filename, 'r', encoding='utf-8') as file:
lines = file.readlines()

for line in lines:
Expand Down Expand Up @@ -204,7 +204,7 @@ def convert_to_header(
array_type: str = "unsigned char",
comment_style: str = "C",
compress: bool = False,
format: str = 'hex',
data_format: str = 'hex',
start: int = 0,
end: Optional[int] = None,
protect: bool = True,
Expand All @@ -222,7 +222,7 @@ def convert_to_header(
array_type (str): Data type of the array in the header file. Defaults to "unsigned char".
comment_style (str): Comment style ("C" or "CPP"). Defaults to "C".
compress (bool): Whether to compress the data. Defaults to False.
format (str): Format of the array data ("hex", "bin", "dec"). Defaults to "hex".
data_format (str): Format of the array data ("hex", "bin", "dec"). Defaults to 'hex'.
start (int): Start byte for conversion. Defaults to 0.
end (Optional[int]): End byte for conversion. Defaults to None.
protect (bool): Whether to include #ifndef protection macros. Defaults to True.
Expand Down Expand Up @@ -254,7 +254,7 @@ def convert_to_header(
'.h', f'_part_{i}.h') if len(parts) > 1 else output_header
array_data = ', '.join(f'0x{b:02X}' for b in part)

with open(part_header, 'w') as header_file:
with open(part_header, 'w', encoding='utf-8') as header_file:
if protect:
header_file.write(f'#ifndef {macro_name}\n')
header_file.write(f'#define {macro_name}\n\n')
Expand All @@ -270,18 +270,17 @@ def convert_to_header(
header_file.write(
f'const unsigned int {size_name}_{i} = sizeof({part_name});\n')
if protect:
header_file.write(f'#endif\n')
header_file.write('#endif\n')

if cpp_class and i == len(parts) - 1:
header_file.write('\n')
header_file.write(
f'class {array_name.capitalize()}Wrapper {{\n')
header_file.write(f'public:\n')
header_file.write('class {array_name.capitalize()}Wrapper {\n')
header_file.write('public:\n')
header_file.write(
f' const {array_type}* data() const {{ return {array_name}; }}\n')
header_file.write(
f' unsigned int size() const {{ return {size_name}; }}\n')
header_file.write(f'}};\n')
header_file.write('};\n')


def convert_to_file(
Expand Down Expand Up @@ -332,7 +331,7 @@ def parse_args(args: List[str]) -> Tuple[str, str, Optional[str], dict]:
"array_type": "unsigned char",
"comment_style": "C",
"compress": False,
"format": 'hex',
"data_format": 'hex',
"start": 0,
"end": None,
"protect": True,
Expand All @@ -353,7 +352,7 @@ def parse_args(args: List[str]) -> Tuple[str, str, Optional[str], dict]:
elif args[i] == "--compress":
options["compress"] = True
elif args[i] == "--format" and i + 1 < len(args):
options["format"] = args[i + 1]
options["data_format"] = args[i + 1]
elif args[i] == "--start" and i + 1 < len(args):
options["start"] = int(args[i + 1])
elif args[i] == "--end" and i + 1 < len(args):
Expand Down Expand Up @@ -413,7 +412,7 @@ def main() -> None:
array_type=options["array_type"],
comment_style=options["comment_style"],
compress=options["compress"],
format=options["format"],
data_format=options["data_format"],
start=options["start"],
end=options["end"],
protect=options["protect"],
Expand Down
20 changes: 10 additions & 10 deletions modules/lithium.pytools/tools/cmake_generator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""
This script automates the generation of CMake build configuration files for C++ projects. It supports multi-directory
project structures, the creation of custom FindXXX.cmake files for third-party libraries, and the use of JSON configuration
files for specifying project settings.
This script automates the generation of CMake build configuration files for C++ projects.
It supports multi-directory project structures, the creation of custom FindXXX.cmake files
for third-party libraries, and the use of JSON configuration files for specifying project settings.
Key features:
1. Multi-directory support with separate CMakeLists.txt for each subdirectory.
Expand Down Expand Up @@ -116,8 +116,8 @@ def generate_cmake(config: ProjectConfig) -> str:

# Dependencies (find_package)
if config.dependencies:
for dep in config.dependencies:
cmake_template += f'find_package({dep} REQUIRED)\n'
for dependency in config.dependencies:
cmake_template += f'find_package({dependency} REQUIRED)\n'

# Subdirectory handling for multi-directory support
if config.subdirs:
Expand Down Expand Up @@ -259,15 +259,15 @@ def parse_arguments():

if args.json:
# Generate CMakeLists.txt from JSON configuration
config = generate_from_json(args.json)
cmake_content = generate_cmake(config)
project_config = generate_from_json(args.json)
cmake_content = generate_cmake(project_config)
save_file(cmake_content)

# Generate FindXXX.cmake files for each dependency specified in the JSON file
for dep in config.dependencies:
find_cmake_content = generate_find_cmake(dep)
for dependency in project_config.dependencies:
find_cmake_content = generate_find_cmake(dependency)
save_file(find_cmake_content, directory="cmake",
filename=f"Find{dep}.cmake")
filename=f"Find{dependency}.cmake")

if args.find_package:
# Generate a single FindXXX.cmake file for the specified dependency
Expand Down
Loading

0 comments on commit 3c63b2b

Please sign in to comment.