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
|
#!/usr/bin/env bash
# keep-latest-n.sh
# 在一个已存在的绝对目录中,按修改时间保留最新的 N 个普通文件。
# 默认只打印计划,不删除。枚举与删除路径由 Python 3 完成,以便安全处理
# 空格、换行和前导短横线文件名,并不跟随符号链接。
set -euo pipefail
usage() {
cat <<'EOF' >&2
用法:
keep-latest-n.sh --directory ABS_DIR --keep N [--glob PATTERN] [--include-hidden] [--json]
keep-latest-n.sh --directory ABS_DIR --keep N [--glob PATTERN] [--include-hidden] [--json] --apply
说明:
默认是 dry-run,只打印将保留和将删除的文件,不修改目录。
必须给出绝对目录和 N(N 为大于等于 1 的十进制整数)。
只处理该目录下的一层普通文件,不递归,不跟随符号链接。
--glob 只匹配文件名,不能包含斜杠;默认 * ,且默认跳过以点开头的文件名。
--apply 才会删除计划中的文件。删除失败会立即停止。
EOF
}
if ! command -v python3 >/dev/null 2>&1; then
printf '%s\n' "错误:需要可用的 python3。" >&2
exit 2
fi
exec python3 - "$@" <<'PY'
import argparse
import fnmatch
import json
import os
import re
import stat
import sys
EXIT_OK = 0
EXIT_USAGE = 2
EXIT_REJECTED = 3
EXIT_APPLY = 4
# 仅拒绝这些路径本身,不把它们的安全子目录一律禁止。
# 家目录也只拒绝精确匹配(含解析后的路径),以便 ~/backups 仍可使用。
FORBIDDEN_EXACT = frozenset(
{
"/",
"/home",
"/root",
"/etc",
"/usr",
"/usr/bin",
"/usr/sbin",
"/usr/local",
"/var",
"/var/tmp",
"/bin",
"/sbin",
"/lib",
"/lib32",
"/lib64",
"/libx32",
"/boot",
"/sys",
"/proc",
"/dev",
"/run",
"/snap",
"/opt",
"/srv",
"/mnt",
"/media",
"/tmp",
}
)
VIRTUAL_PREFIXES = ("/proc/", "/sys/", "/dev/")
def fail(code, message):
print(f"错误:{message}", file=sys.stderr)
sys.exit(code)
def parse_keep(value):
if not re.fullmatch(r"[1-9][0-9]*", value or ""):
fail(
EXIT_USAGE,
" --keep 必须是大于等于 1 的十进制整数,不能有符号、小数或前导零。",
)
return int(value)
def normalize_path(path):
return os.path.normpath(path).rstrip("/") or "/"
def collect_forbidden():
forbidden = set(FORBIDDEN_EXACT)
candidates = []
home = os.environ.get("HOME")
if home:
candidates.append(home)
expanded = os.path.expanduser("~")
if expanded and expanded != "~":
candidates.append(expanded)
for raw in candidates:
if not raw:
continue
abs_path = normalize_path(os.path.abspath(os.path.expanduser(raw)))
forbidden.add(abs_path)
try:
forbidden.add(normalize_path(os.path.realpath(raw)))
except OSError:
pass
return forbidden
def inspect_directory(path):
if not path:
fail(EXIT_USAGE, "必须提供 --directory。")
if path.startswith("~"):
fail(EXIT_USAGE, "请展开 ~ 后传入绝对路径,避免依赖当前用户家目录的隐式展开。")
if not os.path.isabs(path):
fail(EXIT_USAGE, " --directory 必须是绝对路径,避免相对当前工作目录造成误操作。")
if "\x00" in path:
fail(EXIT_USAGE, "目录路径不能包含空字符。")
given = normalize_path(path)
try:
given_st = os.lstat(given)
except OSError as exc:
fail(EXIT_USAGE, f"无法读取目录 {given!r}:{exc}")
if stat.S_ISLNK(given_st.st_mode):
fail(EXIT_REJECTED, f"{given!r} 是符号链接,已拒绝(不跟随符号链接)。")
if not stat.S_ISDIR(given_st.st_mode):
fail(EXIT_USAGE, f"{given!r} 不是目录。")
try:
canonical = normalize_path(os.path.realpath(given))
except OSError as exc:
fail(EXIT_USAGE, f"无法解析目录 {given!r}:{exc}")
forbidden = collect_forbidden()
for candidate in (given, canonical):
if candidate in forbidden:
fail(EXIT_REJECTED, f"{candidate!r} 属于根目录、家目录或其他危险路径,已拒绝。")
if any(candidate.startswith(prefix) for prefix in VIRTUAL_PREFIXES):
fail(EXIT_REJECTED, f"{candidate!r} 位于虚拟文件系统下,已拒绝。")
return given, canonical
def open_directory(path):
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC
if not hasattr(os, "O_NOFOLLOW"):
fail(EXIT_REJECTED, "当前 Python/平台没有 os.O_NOFOLLOW,拒绝继续。")
flags |= os.O_NOFOLLOW
if os.unlink not in os.supports_dir_fd or os.stat not in os.supports_dir_fd:
fail(EXIT_REJECTED, "当前平台不支持 dir_fd,拒绝继续。")
try:
return os.open(path, flags)
except OSError as exc:
fail(EXIT_REJECTED, f"无法打开目录 {path!r}(不跟随符号链接):{exc}")
def validate_glob(pattern):
if pattern is None or pattern == "":
fail(EXIT_USAGE, " --glob 不能为空。")
if "\x00" in pattern or "/" in pattern:
fail(EXIT_USAGE, " --glob 只匹配文件名,不能包含斜杠或空字符,也不会递归。")
return pattern
def list_candidates(dir_fd, pattern, include_hidden):
matched = []
try:
with os.scandir(dir_fd) as iterator:
for entry in iterator:
name = entry.name
if name in (".", ".."):
continue
if "/" in name or "\x00" in name:
fail(EXIT_APPLY, f"目录项 {name!r} 含有非法分隔符,已停止。")
if not include_hidden and name.startswith("."):
continue
if not fnmatch.fnmatchcase(name, pattern):
continue
try:
if entry.is_symlink():
continue
if not entry.is_file(follow_symlinks=False):
continue
info = entry.stat(follow_symlinks=False)
except OSError as exc:
fail(EXIT_APPLY, f"读取目录项 {name!r} 失败,已停止:{exc}")
if not stat.S_ISREG(info.st_mode):
continue
matched.append(
{
"name": name,
"mtime_ns": info.st_mtime_ns,
"size": info.st_size,
"inode": info.st_ino,
}
)
except OSError as exc:
fail(EXIT_APPLY, f"枚举目录失败,已停止:{exc}")
# 先按修改时间从新到旧,时间相同再按文件名升序,排序稳定可复查。
matched.sort(key=lambda item: (-item["mtime_ns"], item["name"]))
return matched
def mock_log_path():
value = os.environ.get("KEEP_LATEST_N_UNLINK_LOG")
if value is None or value == "":
return None
if not os.path.isabs(value):
fail(EXIT_USAGE, "KEEP_LATEST_N_UNLINK_LOG 必须是绝对路径。")
return value
def unlink_one(dir_fd, name, expected_inode=None):
if not name or name in (".", "..") or "/" in name or "\x00" in name:
raise RuntimeError(f"拒绝删除非法文件名 {name!r}")
try:
info = os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
except OSError as exc:
raise RuntimeError(f"删除前复查 {name!r} 失败:{exc}") from exc
if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):
raise RuntimeError(f"拒绝删除 {name!r}:复查时已不是普通文件")
if expected_inode is not None and info.st_ino != expected_inode:
raise RuntimeError(
f"拒绝删除 {name!r}:inode 已从 {expected_inode} 变为 {info.st_ino},停止以免误删被替换的文件"
)
log_path = mock_log_path()
if log_path is not None:
with open(log_path, "a", encoding="utf-8") as handle:
handle.write(json.dumps(name, ensure_ascii=False) + "\n")
return "mocked"
os.unlink(name, dir_fd=dir_fd)
return "unlinked"
def apply_deletes(dir_fd, items):
completed = []
for item in items:
name = item["name"]
try:
action = unlink_one(dir_fd, name, expected_inode=item.get("inode"))
except (OSError, RuntimeError) as exc:
fail(
EXIT_APPLY,
f"已停止删除。已处理 {len(completed)} 个文件,失败文件 {name!r}:{exc}",
)
completed.append({"name": name, "action": action, "inode": item.get("inode")})
return completed
def human_report(payload):
mode = payload["mode"]
print(f"模式:{mode}")
print(f"目录:{payload['directory']}")
print(f"规范路径:{payload['canonical_directory']}")
print(f"保留数量:{payload['keep_n']}")
print(f"匹配规则:fnmatchcase {payload['glob']!r},include_hidden={payload['include_hidden']}")
print(f"匹配到的普通文件:{len(payload['matched'])}")
print("将保留:")
if not payload["keep"]:
print(" (无)")
for item in payload["keep"]:
print(f" KEEP mtime_ns={item['mtime_ns']} name={json.dumps(item['name'], ensure_ascii=False)}")
print("将删除:")
if not payload["delete"]:
print(" (无)")
for item in payload["delete"]:
print(f" DELETE mtime_ns={item['mtime_ns']} name={json.dumps(item['name'], ensure_ascii=False)}")
if payload.get("processed"):
print("本次处理:")
for item in payload["processed"]:
print(f" {item['action'].upper()} name={json.dumps(item['name'], ensure_ascii=False)}")
if mode == "dry-run":
print("这是预览,没有删除任何文件。如需删除,请先核对计划再追加 --apply。")
elif payload.get("unlink_hook") == "KEEP_LATEST_N_UNLINK_LOG":
print("检测到 KEEP_LATEST_N_UNLINK_LOG,已记录计划删除项,没有调用 os.unlink。")
else:
print("已按复查后的文件名在该目录文件描述符上调用 os.unlink。")
def build_parser():
parser = argparse.ArgumentParser(
prog="keep-latest-n.sh",
add_help=True,
description="预览或删除一个目录中除最新 N 个普通文件以外的匹配文件。",
)
parser.add_argument("--directory", required=True, help="绝对目录路径")
parser.add_argument("--keep", required=True, help="至少保留的普通文件数量,整数且 >= 1")
parser.add_argument("--glob", default="*", help="只匹配文件名的模式,默认 *")
parser.add_argument(
"--include-hidden",
action="store_true",
help="包含以点开头的文件名;默认排除。Python fnmatch 的 * 本身会匹配点文件,因此要显式排除",
)
parser.add_argument("--json", action="store_true", help="只输出 JSON")
parser.add_argument(
"--apply",
action="store_true",
help="实际删除计划中的文件;默认只预览",
)
return parser
def main(argv):
parser = build_parser()
try:
args = parser.parse_args(argv)
except SystemExit as exc:
# argparse 的错误已经写到 stderr
raise exc
keep_n = parse_keep(args.keep)
pattern = validate_glob(args.glob)
given, canonical = inspect_directory(args.directory)
dir_fd = open_directory(given)
try:
matched = list_candidates(dir_fd, pattern, args.include_hidden)
keep = matched[:keep_n]
delete = matched[keep_n:]
hook = "KEEP_LATEST_N_UNLINK_LOG" if mock_log_path() else None
processed = []
mode = "apply" if args.apply else "dry-run"
if args.apply:
processed = apply_deletes(dir_fd, delete)
payload = {
"mode": mode,
"directory": given,
"canonical_directory": canonical,
"keep_n": keep_n,
"glob": pattern,
"include_hidden": bool(args.include_hidden),
"matched": matched,
"keep": keep,
"delete": delete,
"processed": processed,
"unlink_hook": hook,
}
if args.json:
print(json.dumps(payload, ensure_ascii=False, indent=2))
else:
human_report(payload)
return EXIT_OK
finally:
os.close(dir_fd)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
PY
|