# 主加载函数 __load_shell_function() { local func_name="$1" local loaded_files=()
for func_file in ~/.config/shell_functions/*.sh; do [[ "$func_file" == *"function_loader.sh" ]] && continue
if [[ -f "$func_file" ]]; then if grep -q -E "^(function[[:space:]]+)?${func_name}[[:space:]]*[({]""$func_file"; then if [[ ! " ${loaded_files[*]} " =~ " ${func_file} " ]]; then source"$func_file" loaded_files+=("$func_file") fi return 0 fi fi done if [ -z "$ZSH_VERSION" ]; then # 如果没有找到函数实现,输出错误信息 echo -e "${COLOR_RED}错误: 未找到函数 ${func_name} 的实现${COLOR_RESET}" >&2 fi return 1 }
# 安全提取函数名 __extract_function_name() { local line="$1" # 严格匹配函数定义行 if [ -n "$ZSH_VERSION" ]; then if [[ "$line" =~ "^[[:space:]]*(function[[:space:]]+)?([a-zA-Z_][a-zA-Z0-9_]*)[[:space:]]*[\(\{]" ]]; then echo"${match[2]}" fi else if [[ "$line" =~ ^[[:space:]]*(function[[:space:]]+)?([a-zA-Z_][a-zA-Z0-9_]*)[[:space:]]*[\(\{] ]]; then echo"${BASH_REMATCH[2]}" fi fi }
# 动态发现所有可用函数 # 动态发现所有可用函数 __discover_shell_functions() { # 使用普通数组代替关联数组 declare -a FUNC_CATEGORIES declare -a SHELL_FUNCTIONS=()
for func_file in ~/.config/shell_functions/*.sh; do [[ "$func_file" == *"function_loader.sh" ]] && continue
if [[ -f "$func_file" ]]; then local category=$(basename"$func_file" .sh) local functions_in_file=()
while IFS= read -r line; do [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ -z "${line//[[:space:]]/}" ]] && continue
local public_functions=() for func in $(printf"%s\n""${functions_in_file[@]}" | sort -u); do [[ "$func" != _* ]] && public_functions+=("$func") done
if ((${#public_functions[@]} > 0)); then FUNC_CATEGORIES+=("${category}:${public_functions[*]}") SHELL_FUNCTIONS+=("${public_functions[@]}") fi fi done
# 显示分类信息 if [ -z "$ZSH_VERSION" ]; then echo -e "${COLOR_BLUE}\n可用命令分类:${COLOR_RESET}" >&2 for entry in"${FUNC_CATEGORIES[@]}"; do local category="${entry%%:*}" localfunctions="${entry#*:}" echo -e "${COLOR_YELLOW}${category}:${COLOR_RESET}" >&2 echo"$functions" | tr' ''\n' | sed 's/^/ /' >&2 done fi
printf"%s\n""${SHELL_FUNCTIONS[@]}" | sort -u }
# 安全创建函数桩 __create_function_stub() { local func="$1"
# 验证函数名是否有效 if [[ "$func" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ -n "$func" ]]; then if ! declare -f "$func" >/dev/null 2>&1; then eval"function ${func}() { __load_shell_function \"${func}\" && \"${func}\" \"\$@\"; }" fi else if [ -z "$ZSH_VERSION" ]; then echo -e "${COLOR_RED}警告: 跳过无效函数名 '${func}'${COLOR_RESET}" >&2 fi fi }
# 主初始化过程 function__init_function_loader() { # 初始化数组 local all_functions=()
# 发现所有函数 while IFS= read -r func; do all_functions+=("$func") done < <(__discover_shell_functions)
# 为每个函数创建桩 for func in"${all_functions[@]}"; do __create_function_stub "$func" done
# 显示统计信息 if [ -z "$ZSH_VERSION" ]; then echo -e "\n${COLOR_GREEN}已注册 ${#all_functions[@]} 个延迟加载函数${COLOR_RESET}" >&2 echo -e "${COLOR_CYAN}提示: 首次使用命令时会自动加载相应模块${COLOR_RESET}" >&2 fi }