import json
import os
import re
import logging
import sys
from pathlib import Path
from shutil import copy2
from datetime import datetime
from utils import resource_path
# -------------------------------
# 日志配置
# -------------------------------
PROJECT_ROOT = Path(__file__).parent.parent.resolve()
LOG_DIR = PROJECT_ROOT / "output" / "log"
LOG_DIR.mkdir(parents=True, exist_ok=True)
LOG_FILE = LOG_DIR / f"range_sync_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
class CLMRangeSynchronizer:
def __init__(self, c_file_path=None, dry_run=False,config_path="config/config.json"):
self.logger = logging.getLogger(__name__)
# === Step 1: 使用 resource_path 解析所有路径 ===
self.config_file_path = resource_path(config_path)
logging.info(f"配置文件: {self.config_file_path}")
if not os.path.exists(self.config_file_path):
raise FileNotFoundError(f"配置文件不存在: {self.config_file_path}")
try:
with open(self.config_file_path, 'r', encoding='utf-8') as f:
self.config = json.load(f)
print(f"配置文件已加载: {self.config_file_path}")
except json.JSONDecodeError as e:
raise ValueError(f"配置文件格式错误,JSON 解析失败: {self.config_file_path}") from e
except Exception as e:
raise RuntimeError(f"读取配置文件时发生未知错误: {e}") from e
self.dry_run = dry_run
if c_file_path is None:
# 使用内置默认 C 文件(被打包进 exe 的)
if "target_c_file" not in self.config:
raise KeyError(" config 文件缺少 'target_c_file' 字段")
internal_c_path = self.config["target_c_file"]
logging.info(f"使用内置 C 文件: {internal_c_path}")
self.c_file_path = Path(resource_path(internal_c_path))
self._is_internal_c_file = True
else:
# 用户传入自定义路径
self.c_file_path = Path(c_file_path)
self._is_internal_c_file = False
if not self.c_file_path.exists():
raise FileNotFoundError(f"找不到 C 源文件: {self.c_file_path}")
self.used_ranges = []
self.array_macros = {} # array_name -> [RANGE_xxx, ...]
self.struct_entries = {} # array_name -> [{"low": int, "high": int}, ...]
self.enum_to_index = {} # RANGE_xxx -> index (from enum)
if "STR_CHANNEL_RANGE" not in self.config:
raise KeyError(" config 文件缺少 'STR_CHANNEL_RANGE' 字段")
self.start_marker = self.config["STR_CHANNEL_RANGE"]
if "END_CHANNEL_RANGE" not in self.config:
raise KeyError(" config 文件缺少 'END_CHANNEL_RANGE' 字段")
self.end_marker = self.config["END_CHANNEL_RANGE"]
def offset_to_lineno(self, content: str, offset: int) -> int:
"""将字符偏移量转换为行号(从1开始)"""
return content.count('\n', 0, offset) + 1
def load_config(self):
"""加载并解析 config.json"""
with open(self.config_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if "used_ranges" not in data:
raise KeyError(" config 文件缺少 'used_ranges' 字段")
valid_ranges = []
for item in data["used_ranges"]:
if isinstance(item, str) and re.match(r'^RANGE_[\w\d_]+_\d+_\d+$', item):
valid_ranges.append(item)
else:
self.logger.warning(f"跳过无效项: {item}")
self.used_ranges = sorted(set(valid_ranges))
self.logger.info(f"已从 {self.config_file_path} 加载 {len(self.used_ranges)} 个有效 RANGE 宏")
def parse_c_arrays(self):
"""解析 C 文件中的 channel_ranges_xxx[] 数组 和 enum range_xxx"""
content = self.c_file_path.read_text(encoding='utf-8')
start_idx = content.find(self.start_marker)
end_idx = content.find(self.end_marker)
if start_idx == -1 or end_idx == -1:
raise ValueError("未找到 CHANNEL RANGES 注释锚点")
block = content[start_idx:end_idx]
start_line = self.offset_to_lineno(content, start_idx)
end_line = self.offset_to_lineno(content, end_idx)
self.logger.info(
f"找到标记范围:{self.start_marker} → 第 {start_line} 行, {self.end_marker} → 第 {end_line} 行")
# === 1. 解析数组:static const struct clm_channel_range xxx[] = { ... };
array_pattern = re.compile(
r'static\s+const\s+struct\s+clm_channel_range\s+(channel_ranges_[\w\d]+)\s*\[\s*\]\s*=\s*\{(.*?)\}\s*;',
re.DOTALL | re.MULTILINE
)
for array_name, body in array_pattern.findall(block):
entries = []
for low, high in re.findall(r'\{\s*(\d+)\s*,\s*(\d+)\s*\}', body):
entries.append({"low": int(low), "high": int(high)})
self.struct_entries[array_name] = entries
self.array_macros[array_name] = [] # 先留空,后续从 enum 填充
self.logger.info(f" 解析数组 {array_name}: {len(entries)} 个范围项")
# === 2. 解析枚举:enum range_xxx { RANGE_A = 0, ... }
enum_pattern = re.compile(r'enum\s+range_([a-z\d_]+)\s*\{([^}]*)\}', re.DOTALL | re.IGNORECASE)
for match in enum_pattern.finditer(block):
suffix = match.group(1) # 如 '2g_40m'
enum_body = match.group(2)
array_name = f"channel_ranges_{suffix}"
if array_name not in self.struct_entries:
self.logger.warning(f" 找到 enum {match.group(0)[:30]}... 但无对应数组")
continue
# 提取 RANGE_xxx = N
for macro, idx_str in re.findall(r'(RANGE_[\w\d_]+)\s*=\s*(\d+)', enum_body):
idx = int(idx_str)
if idx >= len(self.struct_entries[array_name]):
self.logger.warning(f" 索引越界: {macro} = {idx} > 数组长度 {len(self.struct_entries[array_name])}")
continue
self.enum_to_index[macro] = idx
if macro not in self.array_macros[array_name]:
self.array_macros[array_name].append(macro)
self.logger.debug(f" 关联 {macro} → {array_name}[{idx}]")
self.logger.info(f" 总共建立 {len(self.enum_to_index)} 个宏与数组项的映射关系")
def get_array_name_for_range(self, range_macro):
"""根据 RANGE 宏推断应属于哪个数组"""
match = re.match(r'RANGE_([0-9]+[A-Za-z])_([0-9]+)M_', range_macro, re.IGNORECASE)
if not match:
self.logger.warning(f"无法推断数组名: {range_macro}")
return None
band = match.group(1).lower() # '2g'
bw = match.group(2) # '20'
return f"channel_ranges_{band}_{bw}m"
def extract_channels_from_macro(self, macro):
"""
从宏字符串中提取信道范围。
Args:
macro (str): 格式如 RANGE_2G_20M_1_11
Returns:
tuple: (low, high) 或 (None, None)
"""
match = re.search(r'_(\d+)_(\d+)$', macro)
if match:
low = int(match.group(1))
high = int(match.group(2))
return low, high
self.logger.warning(f"宏格式错误,无法提取信道: {macro}")
return None, None
def validate_and_repair(self):
"""确保每个 used_range 都在正确的数组中"""
modified = False
changes = []
for range_macro in self.used_ranges:
array_name = self.get_array_name_for_range(range_macro)
if not array_name:
self.logger.warning(f"无法识别数组类型,跳过: {range_macro}")
continue
# --- 检查宏是否已在 enum 映射中 ---
existing_idx = None
for macro, idx in self.enum_to_index.items():
if macro == range_macro and self.get_array_name_for_range(macro) == array_name:
existing_idx = idx
break
if existing_idx is None:
# 新宏,需分配新索引
next_idx = len(self.struct_entries[array_name])
low, high = self.extract_channels_from_macro(range_macro)
if low is not None and high is not None:
self.struct_entries[array_name].append({"low": low, "high": high})
self.array_macros[array_name].append(range_macro)
self.enum_to_index[range_macro] = next_idx
changes.append(f"扩展枚举: {range_macro} → {{{low}, {high}}} (index={next_idx})")
self.logger.info(f"扩展枚举: {range_macro} → {{{low}, {high}}} (index={next_idx})")
modified = True
else:
self.logger.warning(f"无法解析信道范围: {range_macro}")
if modified and not self.dry_run:
self._write_back_in_block()
self.logger.info("C 文件已更新")
elif modified and self.dry_run:
self.logger.info("DRY-RUN MODE: 有变更但不会写入文件")
else:
self.logger.info(" 所有 RANGE 已存在,无需修改")
if modified:
self.logger.info(f" 共需添加 {len(changes)} 项:\n" + "\n".join(f" → {ch}" for ch in changes))
return modified
def _infer_array_from_enum(self, enum_decl):
"""从 enum 声明推断对应的数组名"""
match = re.search(r'enum\s+range_([a-z\d_]+)', enum_decl)
if match:
return f"channel_ranges_{match.group(1)}"
return None
def _format_array_body(self, structs, indent=" "):
"""格式化结构体数组内容,每行最多4个,数字右对齐"""
items = [f"{{ {s['low']:>2d}, {s['high']:>2d} }}" for s in structs]
lines = []
for i in range(0, len(items), 4):
group = items[i:i + 4]
lines.append(indent + ", ".join(group))
return "\n".join(lines)
def _write_back_in_block(self):
"""安全地一次性更新 C 文件中的数组和枚举定义"""
if self.dry_run:
self.logger.info("DRY-RUN: 跳过写入文件")
return
try:
content = self.c_file_path.read_text(encoding='utf-8')
start_idx = content.find(self.start_marker)
end_idx = content.find(self.end_marker) + len(self.end_marker)
if start_idx == -1 or end_idx == -1:
raise ValueError("未找到 CHANNEL RANGES 标记块")
header = content[:start_idx]
footer = content[end_idx:]
block = content[start_idx:end_idx]
replacements = [] # (start, end, replacement)
# === 工具函数:移除注释避免误匹配 ===
def remove_comments(text):
text = re.sub(r'//.*$', '', text, flags=re.MULTILINE)
text = re.sub(r'/\*.*?\*/', '', text, flags=re.DOTALL)
return text
clean_block = remove_comments(block)
print(" 清理后的 block 内容:")
#print(repr(clean_block[:1500]))
# === 1. 更新 channel_ranges_xxx[] 数组:只在末尾添加新项 ===
array_pattern = re.compile(
r'(static\s+const\s+struct\s+clm_channel_range\s+(channel_ranges_\w+)\s*\[\s*]\s*=\s*\{)([^}]*)}\s*;\s*',
re.DOTALL
)
matches = list(array_pattern.finditer(block))
self.logger.info(f" 找到 {len(matches)} 个 channel_ranges 数组")
for i, match in enumerate(matches):
self.logger.debug(f" 匹配 {i + 1}: 数组名={match.group(2)}, 起始位置={match.start()}")
for match in array_pattern.finditer(block):
array_name = match.group(2)
if array_name not in self.struct_entries:
continue
structs = self.struct_entries[array_name]
body_content = match.group(3) # 不 strip(),保留原始空白
original_end = match.end()
# 提取第一行缩进(用于新行)
first_line = body_content.split('\n')[0] if body_content.strip() else ""
indent_match = re.match(r'^(\s*)', first_line)
indent = indent_match.group(1) if indent_match else " "
# 解析已有 {low, high} 结构体
existing_items = []
item_pattern = r'\{\s*(\d+)\s*,\s*(\d+)\s*\}'
for m in re.finditer(item_pattern, body_content):
low, high = int(m.group(1)), int(m.group(2))
existing_items.append((low, high))
# 查找最后一个结构体结束位置(用于插入点)
all_matches = list(re.finditer(item_pattern, body_content))
if all_matches:
last_match = all_matches[-1]
insert_pos_in_body = body_content.find('}', last_match.start()) + 1
else:
insert_pos_in_body = len(body_content)
# 找出第一个尚未插入的项
inserted_count = len(existing_items)
if inserted_count >= len(structs):
continue
new_item = structs[inserted_count]
low, high = new_item['low'], new_item['high']
# 检查是否已存在
if (low, high) in existing_items:
self.logger.warning(f"已存在 {low}, {high} 项,跳过")
continue
# 构造新条目
formatted_item = f" {{ {low}, {high}}}"
comma = ",\n"
insertion = f"{indent}{formatted_item}{comma}"
# 计算插入位置在整个 block 中的真实 offset
body_start = match.start(3)
insert_offset = body_start + insert_pos_in_body
final_insert = block[:insert_offset] + insertion + block[insert_offset:]
# 重建整个声明
new_decl = f"{match.group(1)}{final_insert[match.start(3):]}{indent}}};"
replacements.append((match.start(), original_end, new_decl))
range_macro = f"RANGE_{array_name.upper().replace('CHANNEL_RANGES_', '').replace('_', '_')}_{low}_{high}"
self.logger.info(f"扩展数组: {range_macro} → {{{low}, {high}}} (index={inserted_count})")
# === 2. 更新 enum range_xxx:精确继承上一行宏名左对齐与 '=' 对齐 ===
enum_pattern = re.compile(r'(enum\s+range_[\w\d_]+\s*\{)([^}]*)\}\s*;', re.DOTALL)
for match in enum_pattern.finditer(block):
enum_name_match = re.search(r'range_([a-zA-Z0-9_]+)', match.group(0))
if not enum_name_match:
continue
inferred_array = f"channel_ranges_{enum_name_match.group(1)}"
if inferred_array not in self.array_macros:
continue
macro_list = self.array_macros[inferred_array]
enum_body = match.group(2)
# 解析已有宏及其值
existing_macros = dict(re.findall(r'(RANGE_[\w\d_]+)\s*=\s*(\d+)', remove_comments(enum_body)))
next_id = len(existing_macros)
if next_id >= len(macro_list):
continue
new_macro = macro_list[next_id]
# 获取非空行
lines = [line for line in enum_body.split('\n') if line.strip()]
last_line = lines[-1] if lines else ""
if not last_line.strip():
# fallback 缩进
line_indent = " "
target_macro_start_col = 4
target_eq_col = 32
else:
indent_match = re.match(r'^(\s*)', last_line)
line_indent = indent_match.group(1) if indent_match else " "
# 展开 tab(统一按 4 空格处理)
expanded_last = last_line.expandtabs(4)
# 提取第一个 RANGE_xxx 宏名
first_macro_match = re.search(r'RANGE_[\w\d_]+', remove_comments(last_line))
if not first_macro_match:
target_macro_start_col = len(line_indent)
target_eq_col = 32
else:
macro_text = first_macro_match.group(0)
macro_start = first_macro_match.start()
# 计算视觉起始列(基于展开后的字符串)
raw_before = last_line[:macro_start]
expanded_before = raw_before.expandtabs(4)
target_macro_start_col = len(expanded_before)
# 找第一个 "=" 的视觉列
eq_match = re.search(r'=\s*\d+', last_line[macro_start:])
if eq_match:
eq_abs_start = macro_start + eq_match.start()
raw_eq_part = last_line[:eq_abs_start]
expanded_eq_part = raw_eq_part.expandtabs(4)
target_eq_col = len(expanded_eq_part)
else:
# fallback
target_eq_col = target_macro_start_col + len(macro_text) + 8
# 现在我们知道:
# - 宏名应该从第 target_macro_start_col 列开始(视觉)
# - `=` 应该出现在 target_eq_col 列
# 计算当前宏名需要多少前置空格才能对齐
current_visual_len = len(new_macro.replace('\t', ' '))
padding_to_eq = max(1, target_eq_col - target_macro_start_col - current_visual_len)
full_padding = ' ' * padding_to_eq
formatted_new = f"{new_macro}{full_padding}= {next_id}"
# 判断是否同行追加(最多 4 个)
clean_last = remove_comments(last_line)
visible_macros = len(re.findall(r'RANGE_[\w\d_]+', clean_last))
if visible_macros < 4 and last_line.strip():
# 同行追加:前面加两个空格分隔
separator = " "
updated_content = last_line + separator + formatted_new + ","
new_body = enum_body.rsplit(last_line, 1)[0] + updated_content
else:
# 换行:使用原始 indent 开头,然后补足到 target_macro_start_col
raw_indent_len = len(line_indent.replace('\t', ' '))
leading_spaces_needed = max(0, target_macro_start_col - raw_indent_len)
prefix_padding = ' ' * leading_spaces_needed
new_line = f"{line_indent}{prefix_padding}{formatted_new},"
trailing = enum_body.rstrip()
maybe_comma = "," if not trailing.endswith(',') else ""
new_body = f"{trailing}{maybe_comma}\n{new_line}"
# 重建 enum
new_enum = f"{match.group(1)}{new_body}\n}};"
replacements.append((match.start(), match.end(), new_enum))
self.logger.info(f"扩展枚举: {new_macro} = {next_id}")
# === 应用替换:倒序防止 offset 错乱 ===
replacements.sort(key=lambda x: x[0], reverse=True)
result_block = block
for start, end, r in replacements:
result_block = result_block[:start] + r + result_block[end:]
# 写回前备份
backup_path = self.c_file_path.with_suffix('.c.bak')
copy2(self.c_file_path, backup_path)
self.logger.info(f"已备份 → {backup_path}")
# 写入新内容
self.c_file_path.write_text(header + result_block + footer, encoding='utf-8')
self.logger.info(f" 成功保存修改: {self.c_file_path}")
except Exception as e:
self.logger.error(f"写回文件失败: {e}", exc_info=True)
raise
def run(self):
self.logger.info("开始同步 CLM RANGE 定义...")
try:
self.load_config()
self.parse_c_arrays()
was_modified = self.validate_and_repair()
if was_modified:
if self.dry_run:
self.logger.info(" 预览模式:检测到变更,但不会写入文件")
else:
self.logger.info(" 同步完成:已成功更新 C 文件")
else:
self.logger.info(" 所有 RANGE 已存在,无需修改")
return was_modified
except Exception as e:
self.logger.error(f" 同步失败: {e}", exc_info=True)
raise
def main():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[
logging.FileHandler(LOG_FILE, encoding='utf-8'),
logging.StreamHandler(sys.stdout)
],
force=True
)
logger = logging.getLogger(__name__)
# 固定配置
c_file_path = "input/wlc_clm_data_6726b0.c"
dry_run = False
log_level = "INFO"
config_path = "config/config.json"
logging.getLogger().setLevel(log_level)
print(f" 开始同步 RANGE 定义...")
print(f" C 源文件: {c_file_path}")
if dry_run:
print(" 启用 dry-run 模式:仅预览变更,不修改文件")
try:
sync = CLMRangeSynchronizer(
c_file_path=None,
dry_run=dry_run,
config_path=config_path,
)
sync.run()
print(" 同步完成!")
print(f" 详细日志已保存至: {LOG_FILE}")
except FileNotFoundError as e:
logger.error(f"文件未找到: {e}")
print(" 请检查文件路径是否正确。")
sys.exit(1)
except PermissionError as e:
logger.error(f"权限错误: {e}")
print(" 无法读取或写入文件,请检查权限。")
sys.exit(1)
except Exception as e:
logger.error(f"程序异常退出: {e}", exc_info=True)
sys.exit(1)
if __name__ == '__main__':
main()
你看全部代码,C:\Users\admin\PyCharmMiscProject\.venv\Scripts\python.exe F:\excle_to_clm\channel\range_sync.py
开始同步 RANGE 定义...
C 源文件: input/wlc_clm_data_6726b0.c
2025-10-21 20:19:59,521 [INFO] root: 资源路径: F:\excle_to_clm
2025-10-21 20:19:59,521 [INFO] root: 配置文件: F:\excle_to_clm\config\config.json
配置文件已加载: F:\excle_to_clm\config\config.json
2025-10-21 20:19:59,521 [INFO] root: 使用内置 C 文件: input/wlc_clm_data_6726b0.c
2025-10-21 20:19:59,521 [INFO] root: 资源路径: F:\excle_to_clm
2025-10-21 20:19:59,521 [INFO] __main__: 开始同步 CLM RANGE 定义...
2025-10-21 20:19:59,522 [INFO] __main__: 已从 F:\excle_to_clm\config\config.json 加载 7 个有效 RANGE 宏
2025-10-21 20:19:59,526 [INFO] __main__: 找到标记范围:// === START CHANNEL RANGES → 第 167 行, // === END CHANNEL RANGES → 第 343 行
2025-10-21 20:19:59,527 [INFO] __main__: 解析数组 channel_ranges_2g_20m: 22 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_2g_40m: 15 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_5g_20m: 39 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_5g_40m: 28 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_5g_80m: 20 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_5g_160m: 6 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_6g_20m: 21 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_6g_40m: 17 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_6g_80m: 24 个范围项
2025-10-21 20:19:59,528 [INFO] __main__: 解析数组 channel_ranges_6g_160m: 18 个范围项
2025-10-21 20:19:59,529 [INFO] __main__: 解析数组 channel_ranges_6g_320m: 9 个范围项
2025-10-21 20:19:59,529 [INFO] __main__: 总共建立 198 个宏与数组项的映射关系
2025-10-21 20:19:59,529 [INFO] __main__: 扩展枚举: RANGE_2G_40M_4_8 → {4, 8} (index=15)
清理后的 block 内容:
2025-10-21 20:19:59,535 [INFO] __main__: 找到 0 个 channel_ranges 数组
2025-10-21 20:19:59,535 [INFO] __main__: 扩展枚举: RANGE_2G_40M_4_8 = 15
2025-10-21 20:19:59,538 [INFO] __main__: 已备份 → F:\excle_to_clm\input\wlc_clm_data_6726b0.c.bak
2025-10-21 20:19:59,542 [INFO] __main__: 成功保存修改: F:\excle_to_clm\input\wlc_clm_data_6726b0.c
2025-10-21 20:19:59,543 [INFO] __main__: C 文件已更新
2025-10-21 20:19:59,543 [INFO] __main__: 共需添加 1 项:
→ 扩展枚举: RANGE_2G_40M_4_8 → {4, 8} (index=15)
2025-10-21 20:19:59,543 [INFO] __main__: 同步完成:已成功更新 C 文件
同步完成!
详细日志已保存至: F:\excle_to_clm\output\log\range_sync_20251021_201959.log
进程已结束,退出代码为 0
输出日志中在 # === 2. 解析枚举:enum range_xxx { RANGE_A = 0, ... }
enum_pattern = re.compile(r'enum\s+range_([a-z\d_]+)\s*\{([^}]*)\}', re.DOTALL | re.IGNORECASE)
for match in enum_pattern.finditer(block):
suffix = match.group(1) # 如 '2g_40m'
enum_body = match.group(2)
array_name = f"channel_ranges_{suffix}"
if array_name not in self.struct_entries:
self.logger.warning(f" 找到 enum {match.group(0)[:30]}... 但无对应数组")
continue
完全没有反映
最新发布