Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·627 lines (497 loc) · 16.7 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·627 lines (497 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#!/bin/bash
# ============================================
# Hammerspoon Configuration Management Tool
# ============================================
# 功能: 模块化配置管理安装器
# 要求: Bash 3.2+, macOS, Hammerspoon
# ============================================
set -euo pipefail
# ============================================
# 全局常量
# ============================================
readonly SCRIPT_VERSION="1.0.0"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly MODULES_DIR="${SCRIPT_DIR}/modules"
readonly HAMMERSPOON_DIR="${HOME}/.hammerspoon"
readonly INIT_FILE="${HAMMERSPOON_DIR}/init.lua"
readonly BACKUP_DIR="${HAMMERSPOON_DIR}/backups"
# ============================================
# 颜色定义 (兼容 Bash 3.2)
# ============================================
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly NC='\033[0m'
# ============================================
# 日志函数
# ============================================
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
log_debug() {
[[ "${DEBUG:-0}" -eq 1 ]] && echo -e "${CYAN}[DEBUG]${NC} $1"
}
# ============================================
# 错误处理
# ============================================
error_exit() {
log_error "$1"
exit 1
}
cleanup_on_error() {
local line=$1
log_error "脚本在第 ${line} 行发生错误"
exit 1
}
trap 'cleanup_on_error $LINENO' ERR
# ============================================
# 环境检查
# ============================================
check_os() {
log_info "检查操作系统..."
if [[ "$(uname -s)" != "Darwin" ]]; then
error_exit "此脚本仅支持 macOS 系统"
fi
local os_version
os_version="$(sw_vers -productVersion)"
log_success "操作系统检查通过: macOS ${os_version}"
}
check_bash_version() {
log_info "检查 Bash 版本..."
local major_version="${BASH_VERSINFO[0]}"
local minor_version="${BASH_VERSINFO[1]}"
if [[ ${major_version} -lt 3 ]] || [[ ${major_version} -eq 3 && ${minor_version} -lt 2 ]]; then
error_exit "需要 Bash 3.2 或更高版本,当前版本: ${BASH_VERSION}"
fi
log_success "Bash 版本检查通过: ${BASH_VERSION}"
}
check_hammerspoon() {
log_info "检查 Hammerspoon 是否已安装..."
if [[ -d "/Applications/Hammerspoon.app" ]]; then
log_success "Hammerspoon 已安装 (/Applications)"
return 0
fi
if [[ -d "${HOME}/Applications/Hammerspoon.app" ]]; then
log_success "Hammerspoon 已安装 (~/Applications)"
return 0
fi
if command -v brew &>/dev/null; then
if brew list --cask 2>/dev/null | grep -q "^hammerspoon$"; then
log_success "Hammerspoon 已通过 Homebrew 安装"
return 0
fi
fi
log_warning "未检测到 Hammerspoon"
# 尝试自动安装
if command -v brew &>/dev/null; then
log_info "正在通过 Homebrew 安装 Hammerspoon..."
if brew install --cask hammerspoon; then
log_success "Hammerspoon 安装成功"
log_info "请按 Cmd+Space 搜索 Hammerspoon 并启动,然后重新运行此脚本"
return 0
else
error_exit "Hammerspoon 安装失败"
fi
else
log_error "未检测到 Homebrew,无法自动安装"
log_info "请按以下步骤手动安装:"
log_info " 1. 安装 Homebrew: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
log_info " 2. 安装 Hammerspoon: brew install --cask hammerspoon"
log_info " 3. 启动 Hammerspoon 后重新运行此脚本"
exit 1
fi
}
# ============================================
# 路径安全验证
# ============================================
validate_path() {
local path="$1"
local base_dir="$2"
if [[ "${path}" == *".."* ]]; then
error_exit "路径包含非法字符 '..': ${path}"
fi
if [[ "${path}" == /* ]]; then
error_exit "路径必须是相对路径: ${path}"
fi
local full_path
full_path="$(cd "${base_dir}" && pwd)/${path}"
local resolved_path
resolved_path="$(cd "${base_dir}" && cd "$(dirname "${path}")" && pwd)/$(basename "${path}")"
if [[ "${resolved_path}" != "${base_dir}"* ]]; then
error_exit "路径遍历检测失败: ${path}"
fi
return 0
}
# ============================================
# INI 解析
# ============================================
parse_ini() {
local file_path="$1"
local prefix="${2:-}"
local current_section=""
local line_num=0
if [[ ! -f "${file_path}" ]]; then
error_exit "配置文件不存在: ${file_path}"
fi
while IFS= read -r line || [[ -n "${line}" ]]; do
((line_num++))
# Remove carriage return
line=$(echo "${line}" | tr -d '\r')
# Skip empty lines
[[ -z "${line}" ]] && continue
# Skip comment lines (starts with # or ;)
local trimmed_line="${line#"${line%%[![:space:]]*}"}"
[[ "${trimmed_line}" == \#* ]] && continue
[[ "${trimmed_line}" == \;* ]] && continue
# Parse section [section]
if echo "${line}" | grep -qE '^\[.+\]$'; then
current_section=$(echo "${line}" | sed 's/^\[//;s/\]$//')
log_debug "解析到 Section: ${current_section}"
continue
fi
# Parse key=value
if echo "${line}" | grep -qE '^[a-zA-Z0-9_-]+[[:space:]]*='; then
local key=$(echo "${line}" | sed 's/[[:space:]]*=.*$//')
local value=$(echo "${line}" | sed 's/^[^=]*=[[:space:]]*//')
# Trim whitespace from value
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
local var_name=""
if [[ -n "${current_section}" ]]; then
var_name="${prefix}${current_section}_${key}"
else
var_name="${prefix}${key}"
fi
eval "${var_name}=\"${value}\""
log_debug "设置变量: ${var_name}='${value}'"
fi
done < "${file_path}"
}
# ============================================
# 模块发现 (Bash 3.2 兼容 - 使用临时文件替代关联数组)
# ============================================
FOUND_MODULES=()
TEMP_DIR=""
cleanup_temp() {
if [[ -n "${TEMP_DIR}" && -d "${TEMP_DIR}" ]]; then
rm -rf "${TEMP_DIR}"
fi
}
init_temp_dir() {
TEMP_DIR=$(mktemp -d /tmp/hammerspoon_install.XXXXXX)
trap cleanup_temp EXIT
}
# 设置模块属性 (存储在临时文件中)
set_module_attr() {
local module="$1"
local attr="$2"
local value="$3"
local file="${TEMP_DIR}/${module}_${attr}"
echo "${value}" > "${file}"
}
# 获取模块属性
get_module_attr() {
local module="$1"
local attr="$2"
local file="${TEMP_DIR}/${module}_${attr}"
if [[ -f "${file}" ]]; then
cat "${file}"
fi
}
discover_modules() {
log_info "发现模块..."
# 初始化临时目录
init_temp_dir
if [[ ! -d "${MODULES_DIR}" ]]; then
log_warning "模块目录不存在: ${MODULES_DIR}"
return 0
fi
local count=0
while IFS= read -r -d '' config_file; do
log_debug "发现配置文件: ${config_file}"
local module_dir
module_dir="$(dirname "${config_file}")"
local module_name
module_name="$(basename "${module_dir}")"
if [[ "${module_name}" == *".."* ]] || [[ "${module_name}" == /* ]]; then
log_warning "跳过非法模块名: ${module_name}"
continue
fi
local prefix="MOD_"
parse_ini "${config_file}" "${prefix}"
if [[ -z "${MOD_name:-}" ]]; then
log_warning "模块 ${module_name} 缺少 name 字段,跳过"
continue
fi
if [[ -z "${MOD_path:-}" ]]; then
log_warning "模块 ${module_name} 缺少 path 字段,跳过"
continue
fi
local entry_path="${module_dir}/${MOD_path}"
if [[ ! -f "${entry_path}" ]]; then
log_warning "模块 ${module_name} 的入口文件不存在: ${entry_path}"
continue
fi
FOUND_MODULES+=("${module_name}")
set_module_attr "${module_name}" "name" "${MOD_name}"
set_module_attr "${module_name}" "description" "${MOD_description:-}"
set_module_attr "${module_name}" "path" "${entry_path}"
set_module_attr "${module_name}" "enable" "${MOD_enable:-true}"
count=$((count + 1))
log_info "发现模块: ${MOD_name} (${module_name})"
done < <(find "${MODULES_DIR}" -name "init.conf" -type f -print0 2>/dev/null)
log_success "共发现 ${count} 个模块"
}
# ============================================
# 生成 Hammerspoon 配置
# ============================================
generate_init_lua() {
log_info "生成 Hammerspoon 配置..."
mkdir -p "${BACKUP_DIR}"
if [[ -f "${INIT_FILE}" ]]; then
local backup_file="${BACKUP_DIR}/init.lua.backup.$(date +%Y%m%d_%H%M%S)"
cp "${INIT_FILE}" "${backup_file}"
log_info "已备份现有配置: ${backup_file}"
fi
local temp_file="${INIT_FILE}.tmp.$$"
cat > "${temp_file}" << 'HEADER'
-- ============================================
-- Hammerspoon Configuration
-- Auto-generated by install.sh
-- DO NOT EDIT THIS FILE DIRECTLY
-- ============================================
HEADER
cat >> "${temp_file}" << 'LOADER'
-- 模块管理器
local ModuleManager = {
modules = {},
enabledModules = {}
}
function ModuleManager.load(name, path)
local success, result = pcall(function()
return dofile(path)
end)
if success then
ModuleManager.modules[name] = result
print(string.format("[ModuleManager] 已加载模块: %s", name))
return result
else
print(string.format("[ModuleManager] 加载模块失败: %s - %s", name, result))
return nil
end
end
function ModuleManager.enable(name)
local mod = ModuleManager.modules[name]
if mod and mod.init then
mod.init()
ModuleManager.enabledModules[name] = true
end
end
function ModuleManager.get(name)
return ModuleManager.modules[name]
end
LOADER
echo "" >> "${temp_file}"
echo "-- ============================================" >> "${temp_file}"
echo "-- 加载模块" >> "${temp_file}"
echo "-- ============================================" >> "${temp_file}"
echo "" >> "${temp_file}"
local enabled_count=0
for module in "${FOUND_MODULES[@]}"; do
local module_name=$(get_module_attr "${module}" "name")
local module_path=$(get_module_attr "${module}" "path")
local module_enable=$(get_module_attr "${module}" "enable")
local relative_path="${module_path#${SCRIPT_DIR}/}"
echo "-- 模块: ${module_name}" >> "${temp_file}"
echo "ModuleManager.load(\"${module}\", \"${SCRIPT_DIR}/${relative_path}\")" >> "${temp_file}"
if [[ "${module_enable}" == "true" ]]; then
echo "ModuleManager.enable(\"${module}\")" >> "${temp_file}"
enabled_count=$((enabled_count + 1))
else
echo "-- ModuleManager.enable(\"${module}\") -- 已禁用" >> "${temp_file}"
fi
echo "" >> "${temp_file}"
done
cat >> "${temp_file}" << 'FOOTER'
-- ============================================
-- 全局热键
-- ============================================
hs.hotkey.bind({"ctrl", "option", "cmd"}, "R", function()
hs.notify.new({
title = "Hammerspoon",
informativeText = "正在重新加载配置...",
withdrawAfter = 2
}):send()
hs.reload()
end)
hs.hotkey.bind({"ctrl", "option", "cmd"}, "M", function()
local modList = {}
for name, _ in pairs(ModuleManager.modules) do
table.insert(modList, name)
end
hs.notify.new({
title = "已加载模块",
informativeText = table.concat(modList, ", "),
withdrawAfter = 5
}):send()
end)
hs.notify.new({
title = "Hammerspoon",
informativeText = "配置已加载完成",
withdrawAfter = 3
}):send()
print("========================================")
print("Hammerspoon 配置已加载")
print("========================================")
FOOTER
mv "${temp_file}" "${INIT_FILE}"
chmod 600 "${INIT_FILE}"
log_success "配置已生成: ${INIT_FILE}"
log_info "共启用 ${enabled_count} 个模块"
}
# ============================================
# Hammerspoon 目录权限设置
# ============================================
setup_permissions() {
log_info "设置 Hammerspoon 目录权限..."
if [[ ! -d "${HAMMERSPOON_DIR}" ]]; then
mkdir -p "${HAMMERSPOON_DIR}"
log_info "创建目录: ${HAMMERSPOON_DIR}"
fi
chmod 700 "${HAMMERSPOON_DIR}"
if [[ -d "${BACKUP_DIR}" ]]; then
chmod 700 "${BACKUP_DIR}"
fi
if [[ -f "${INIT_FILE}" ]]; then
chmod 600 "${INIT_FILE}"
fi
log_success "权限设置完成"
}
# ============================================
# Hammerspoon 控制
# ============================================
reload_hammerspoon() {
log_info "重新加载 Hammerspoon 配置..."
if pgrep -x "Hammerspoon" &>/dev/null; then
if command -v hs &>/dev/null && hs -c "hs.reload()" &>/dev/null; then
log_success "Hammerspoon 配置已重新加载"
else
osascript -e 'tell application "Hammerspoon" to execute lua code "hs.reload()"' 2>/dev/null || {
log_warning "无法自动重新加载,请手动按 Cmd+Option+Ctrl+R"
}
fi
else
log_warning "Hammerspoon 未运行,请手动启动"
open -a "Hammerspoon" || true
fi
}
# ============================================
# 显示帮助信息
# ============================================
show_help() {
cat << 'HELP'
========================================
Hammerspoon Configuration Management Tool
========================================
用法: ./install.sh [选项]
选项:
-h, --help 显示此帮助信息
-d, --debug 启用调试模式
-n, --dry-run 试运行(不实际执行)
--no-reload 安装后不重新加载 Hammerspoon
示例:
./install.sh # 正常安装
./install.sh -d # 调试模式安装
./install.sh --dry-run # 试运行
========================================
HELP
}
# ============================================
# 主函数
# ============================================
main() {
local dry_run=false
local no_reload=false
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
show_help
exit 0
;;
-d|--debug)
DEBUG=1
shift
;;
-n|--dry-run)
dry_run=true
shift
;;
--no-reload)
no_reload=true
shift
;;
*)
log_error "未知选项: $1"
show_help
exit 1
;;
esac
done
echo "========================================"
echo " Hammerspoon 配置管理工具 v${SCRIPT_VERSION}"
echo "========================================"
echo ""
if [[ "${dry_run}" == true ]]; then
log_warning "试运行模式 - 不会实际修改任何文件"
fi
check_os
check_bash_version
check_hammerspoon
echo ""
discover_modules
if [[ ${#FOUND_MODULES[@]} -eq 0 ]]; then
log_warning "未发现任何模块"
fi
echo ""
if [[ "${dry_run}" == true ]]; then
log_info "试运行完成"
exit 0
fi
setup_permissions
generate_init_lua
if [[ "${no_reload}" == false ]]; then
reload_hammerspoon
fi
echo ""
echo "========================================"
log_success "安装完成!"
echo "========================================"
echo ""
echo "已加载模块:"
for module in "${FOUND_MODULES[@]}"; do
local mod_name=$(get_module_attr "${module}" "name")
local mod_enable=$(get_module_attr "${module}" "enable")
local status="禁用"
[[ "${mod_enable}" == "true" ]] && status="启用"
echo " - ${mod_name} (${module}): ${status}"
done
echo ""
echo "快捷键:"
echo " Ctrl+Option+Cmd+R - 重新加载配置"
echo " Ctrl+Option+Cmd+M - 显示已加载模块"
echo ""
echo "配置文件: ${INIT_FILE}"
echo "========================================"
}
main "$@"