migrate_kb_paths.py
8.95 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
"""知识库物理路径规整:把存量库搬到规范布局下。
规范布局(与 config.py / kb_paths.py 一致):
- 内置公共基础库 → ware/kb/base/main/{raw,wiki}
- 其余基础库 → ware/kb/base/<库id>/{raw,wiki}
- 部门库 → ware/kb/dept/<库id>/{raw,wiki}
存量里有三类偏差需要纠正:
1. 内置公共基础库还落在历史目录 ware/kb/base/comm(更早还有 ware/kb/comm);
2. 大量库的 root_dir 尾段用的是**绑定部门的 dept_id**,而不是库自身的 id;
3. 更早期的库没有 base/dept 这层,直接是 ware/kb/<uuid>。
搬迁三件事一起做,缺一不可:
- 磁盘目录 rename;
- DB 的 wiki_kb_info.root_dir、wiki_files.raw_path、wiki_file_pages.page_path 前缀改写;
- **页面正文里的路径改写**——index.md 的 `path:` 字段与 log.md 的摄入/摄出留痕里嵌了
项目根相对路径,不改就会指向不存在的位置。
已软删的库(del_flag=1)默认原地不动:它们既不可恢复也不参与检索,搬迁只有风险没有收益。
需要一并规整时加 --include-deleted。
用法:
python -m scripts.migrate_kb_paths # 只打印计划(dry-run,默认)
python -m scripts.migrate_kb_paths --apply # 实际执行
python -m scripts.migrate_kb_paths --apply --include-deleted
"""
from __future__ import annotations
import argparse
import asyncio
import logging
import os
import shutil
import sys
from sqlalchemy import select
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from config import BASE_DIR # noqa: E402
from src.database.models import WikiFile, WikiFilePage, WikiKbInfo # noqa: E402
from src.database.session import AsyncSessionLocal # noqa: E402
from src.services.oa import enums # noqa: E402
from src.services.oa.kb_provision import BASE_KB_ROOT, LEGACY_BASE_KB_ROOTS # noqa: E402
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("migrate_kb_paths")
# 只改写这些扩展名的正文(wiki 页面与留痕都是 markdown)
_TEXT_SUFFIXES = (".md",)
def expected_root(kb: WikiKbInfo) -> str:
"""该库应有的 root_dir(项目根相对,POSIX 风格)。"""
if (kb.root_dir or "") in LEGACY_BASE_KB_ROOTS or kb.root_dir == BASE_KB_ROOT:
# 内置公共基础库:认历史 root_dir,不按 id 命名
return BASE_KB_ROOT
bucket = "base" if kb.kb_type == enums.KB_BASE else "dept"
return f"ware/kb/{bucket}/{kb.id}"
def _abs(rel: str) -> str:
return os.path.join(BASE_DIR, rel.replace("/", os.sep))
def _has_files(path: str) -> bool:
"""目录树里是否存在任何文件(只有空子目录不算有内容)。"""
for _dirpath, _dirnames, filenames in os.walk(path):
if filenames:
return True
return False
def move_dir(old_rel: str, new_rel: str) -> str:
"""把 old_rel 目录搬到 new_rel。返回一句话结果说明。
目标已存在但**不含任何文件**(config 启动时 makedirs 出来的 raw/wiki 空壳)时先删掉再搬;
目标已有文件则拒绝,避免把两个库的内容混在一起。
"""
old_abs, new_abs = _abs(old_rel), _abs(new_rel)
if not os.path.isdir(old_abs):
os.makedirs(new_abs, exist_ok=True)
return "旧目录不存在,仅建新目录"
if os.path.isdir(new_abs):
if _has_files(new_abs):
raise RuntimeError(f"目标目录已存在且含文件,拒绝合并: {new_rel}")
shutil.rmtree(new_abs)
os.makedirs(os.path.dirname(new_abs), exist_ok=True)
shutil.move(old_abs, new_abs)
return "已搬迁"
def rewrite_texts(root_rel: str, old_rel: str, new_rel: str) -> int:
"""改写 root_rel 目录下所有 markdown 里出现的 old_rel → new_rel。返回改动文件数。
路径在正文里以项目根相对形式出现(如 index.md 的 `path: ware/kb/dept/<id>/wiki/x.md`),
直接做字符串替换即可;old_rel 含 uuid,不会误伤其它内容。
"""
changed = 0
for dirpath, _dirnames, filenames in os.walk(_abs(root_rel)):
for name in filenames:
if not name.endswith(_TEXT_SUFFIXES):
continue
path = os.path.join(dirpath, name)
try:
with open(path, encoding="utf-8") as f:
text = f.read()
except (UnicodeDecodeError, OSError) as exc:
logger.warning(" 正文读取失败,跳过: %s (%s)", path, exc)
continue
if old_rel not in text:
continue
with open(path, "w", encoding="utf-8") as f:
f.write(text.replace(old_rel, new_rel))
changed += 1
return changed
async def _rewrite_db_paths(session, old_rel: str, new_rel: str) -> tuple[int, int]:
"""改写 DB 里以 old_rel 打头的 raw_path / page_path。返回 (文件数, 页面数)。"""
files = (
await session.execute(
select(WikiFile).where(WikiFile.raw_path.like(f"{old_rel}/%"))
)
).scalars().all()
for f in files:
f.raw_path = new_rel + f.raw_path[len(old_rel):]
pages = (
await session.execute(
select(WikiFilePage).where(WikiFilePage.page_path.like(f"{old_rel}/%"))
)
).scalars().all()
for p in pages:
p.page_path = new_rel + p.page_path[len(old_rel):]
return len(files), len(pages)
async def migrate(apply: bool, include_deleted: bool) -> dict:
planned = migrated = skipped = failed = 0
# 先把要处理的库读成纯数据:每个库各用独立事务搬迁,一个失败不牵连其它,
# 也避免 rollback 让共享 session 里的 ORM 对象过期(属性访问会触发同步 IO 而报 MissingGreenlet)。
async with AsyncSessionLocal() as session:
stmt = select(WikiKbInfo)
if not include_deleted:
stmt = stmt.where(WikiKbInfo.del_flag == enums.DEL_NORMAL)
rows = (await session.execute(stmt.order_by(WikiKbInfo.kb_type))).scalars().all()
kbs = [
{
"id": kb.id,
"kb_type": kb.kb_type,
"kb_name": kb.kb_name,
"old": (kb.root_dir or "").replace("\\", "/"),
"new": expected_root(kb),
}
for kb in rows
]
logger.info("待检查知识库 %d 个(include_deleted=%s)", len(kbs), include_deleted)
# 目标路径撞车就立刻停手,别搬到一半
targets: dict[str, str] = {}
for kb in kbs:
if kb["new"] in targets:
raise RuntimeError(f"目标路径冲突: {kb['new']} 同时被 {targets[kb['new']]} 与 {kb['id']} 占用")
targets[kb["new"]] = kb["id"]
for kb in kbs:
old_rel, new_rel = kb["old"], kb["new"]
if old_rel == new_rel:
skipped += 1
continue
planned += 1
exists = os.path.isdir(_abs(old_rel))
logger.info(
"[%s] %s\n %s → %s%s",
kb["kb_type"], kb["kb_name"], old_rel or "(空)", new_rel,
"" if exists else " (磁盘无旧目录)",
)
if not apply:
continue
# 顺序:先搬磁盘再改 DB。磁盘失败则 DB 不动,两边仍一致;
# 磁盘成功而 DB 失败时重跑即可自愈——DB 里仍是旧路径,而旧目录已不在,
# 走「旧目录不存在」分支不会破坏已搬好的内容,随后补上 DB 更新。
try:
note = move_dir(old_rel, new_rel)
touched = rewrite_texts(new_rel, old_rel, new_rel) if old_rel else 0
async with AsyncSessionLocal() as session:
n_files, n_pages = await _rewrite_db_paths(session, old_rel, new_rel)
record = await session.get(WikiKbInfo, kb["id"])
if record is not None:
record.root_dir = new_rel
await session.commit()
migrated += 1
logger.info(
" %s;正文改写 %d 个文件,DB raw_path %d 条 / page_path %d 条",
note, touched, n_files, n_pages,
)
except Exception as exc: # noqa: BLE001
failed += 1
logger.error(" 失败,该库保持原状: %s", exc)
result = {"planned": planned, "migrated": migrated, "unchanged": skipped, "failed": failed}
logger.info("完成: %s", result)
if not apply and planned:
logger.info("以上仅为计划(dry-run)。确认无误后加 --apply 执行。")
return result
def main() -> None:
parser = argparse.ArgumentParser(description="知识库物理路径规整")
parser.add_argument("--apply", action="store_true", help="实际执行(默认只打印计划)")
parser.add_argument("--include-deleted", action="store_true", help="连已软删的库一起规整")
args = parser.parse_args()
asyncio.run(migrate(apply=args.apply, include_deleted=args.include_deleted))
if __name__ == "__main__":
main()