-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy patherase_history.py
More file actions
executable file
·437 lines (368 loc) · 13.2 KB
/
erase_history.py
File metadata and controls
executable file
·437 lines (368 loc) · 13.2 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
#!/usr/bin/env python
########################################################################
# erase_history.py: Zsh History Tail Line Eraser
#
# Description:
# This script deletes recently executed history lines from the Zsh history
# file (~/.zsh_history) in order to quickly remove mistyped or unintended
# lines recorded in the shell history. When the last history entry
# corresponds to this script invocation, that entry is preserved and
# the preceding N lines are removed instead.
#
# Author: id774 (More info: http://id774.net)
# Source Code: https://github.com/id774/scripts
# License: The GPL version 3, or LGPL version 3 (Dual License).
# Contact: idnanashi@gmail.com
#
# Usage:
# erase_history.py # removes last 1 line (default)
# erase_history.py -2
# erase_history.py -n 2
# erase_history.py -q
# erase_history.py -h | --help
# erase_history.py -v | --version
#
# Options:
# - erase_history.py -2
# Removes the last 2 history lines (numeric shorthand).
# - erase_history.py -n 2
# Removes the last 2 history lines (explicit option).
# - erase_history.py -q | --quiet
# Suppress all output.
#
# Default behavior:
# - Removes the most recently appended N lines from ~/.zsh_history
# (default: 1 line).
# - If the last history entry is this script invocation, the script
# keeps that entry and removes the preceding N lines instead.
#
# By default, the deleted lines themselves are printed to standard
# output exactly as they appeared in the history file. This allows
# users to visually confirm what will be removed with an explicit info prefix.
#
# When quiet mode is enabled (-q / --quiet), no output is produced.
# In quiet mode, the script still performs the deletion but suppresses
# all standard output.
#
# Confirmation:
# - When quiet mode is not enabled, this script prompts for confirmation.
# - Only "y" or "yes" (case-insensitive) performs deletion.
#
# Safety:
# - Maximum removable lines: 10
#
# Limitations:
# - Multiline history entries recorded as multiple physical lines in the
# history file are not treated as a single entry.
# - Removing N lines may therefore remove part of a multiline entry.
#
# Notes:
# - This script operates strictly on a line basis.
# - When the last history entry is this script invocation, deletion is
# applied to the preceding lines so that the invocation itself
# remains visible in history.
# - The file is updated atomically to avoid history corruption.
# - Modifying ~/.zsh_history does not automatically update the in-memory
# history of already running shell sessions. Users may need to reload
# the history manually (for example: `fc -R ~/.zsh_history` or
# `history -n`) or open a new shell session.
# - When multiple shell sessions are active, concurrent history writes may
# reintroduce entries after this script modifies the history file.
# This is expected behavior when SHARE_HISTORY or APPEND_HISTORY is enabled.
# - Behavior may vary depending on zsh history options such as
# APPEND_HISTORY or SHARE_HISTORY, which control how history is shared
# and synchronized across sessions.
# - Self invocation detection is based on the script file path.
# The command is resolved via PATH when necessary so that
# invocations such as "erase_history.py" are correctly detected
# even when executed without a path prefix.
# - Self invocation detection is based on the last line in the history file.
# Depending on history flush timing, the last line may not be the most
# recently executed command.
# - This allows correct detection when the script is executed via
# a command name, full path, or symlink.
# - Invocations through shell aliases or functions may not be detected
# as self invocation because the original command name is not stored
# in the history file.
# - To treat aliases as self invocation, set ERASE_HISTORY_SELF_NAMES
# to a comma-separated list of command names (e.g. "eh,hh").
# When the first token in the history entry matches one of these names,
# it is considered self invocation.
#
# Requirements:
# - Python Version: 3.1 or later
#
# Version History:
# v1.2 2026-02-25
# Detect self invocation by script path instead of command name.
# Support alias-based self invocation via ERASE_HISTORY_SELF_NAMES.
# v1.1 2026-02-15
# Keep this script invocation in history when it is the last entry.
# v1.0 2026-01-10
# Initial release.
#
########################################################################
import os
import sys
import tempfile
MAX_REMOVE_LINES = 10
def usage():
"""
Display the script header as usage and exit.
This function extracts the header comment block from this script
itself and prints it verbatim, ensuring that the usage output
always matches the documented behavior.
"""
script_path = os.path.abspath(__file__)
in_header = False
try:
with open(script_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip().startswith('#' * 10):
if not in_header:
in_header = True
continue
else:
break
if in_header and line.startswith('#'):
if line.startswith('# '):
print(line[2:], end='')
else:
print(line[1:], end='')
except Exception as e:
print("Error reading usage information: %s" % str(e), file=sys.stderr)
sys.exit(1)
sys.exit(0)
def parse_args(argv):
"""
Parse command-line arguments and determine the number of history lines to remove.
Supported patterns:
- No arguments -> remove 1 line
- -<digits> (e.g. -2) -> remove <digits> lines
- -n <digits> -> remove <digits> lines
Args:
argv (list): Argument list excluding the script name.
Returns:
tuple: (number_of_lines, quiet)
Exits:
2: On invalid arguments.
"""
n = 1
quiet = False
if not argv:
return n, quiet
if len(argv) == 1:
a = argv[0]
if a in ('-h', '--help', '-v', '--version'):
usage()
if a in ('-q', '--quiet'):
quiet = True
return n, quiet
if a.startswith('-') and len(a) > 1 and a[1:].isdigit():
n = int(a[1:], 10)
else:
print("[ERROR] Unknown option: %s" % a, file=sys.stderr)
sys.exit(2)
return n, quiet
if len(argv) == 2:
if argv[0] in ('-n', '--lines'):
if not argv[1].isdigit():
print("[ERROR] Invalid number for -n: %s" % argv[1], file=sys.stderr)
sys.exit(2)
n = int(argv[1], 10)
return n, quiet
if argv[0] in ('-q', '--quiet'):
quiet = True
if argv[1].startswith('-') and argv[1][1:].isdigit():
n = int(argv[1][1:], 10)
return n, quiet
if argv and (argv[0] in ('-h', '--help', '-v', '--version')):
usage()
print("[ERROR] Invalid arguments", file=sys.stderr)
sys.exit(2)
def validate_n(n):
"""
Validate the requested number of history lines to remove.
Args:
n (int): Number of lines.
Exits:
2: If n is less than 1.
"""
if n <= 0:
print("[ERROR] N must be >= 1", file=sys.stderr)
sys.exit(2)
if n > MAX_REMOVE_LINES:
print("[ERROR] N must be <= %d" % MAX_REMOVE_LINES, file=sys.stderr)
sys.exit(2)
def is_self_invocation(history_line):
"""
Return True if the given history line looks like this script invocation.
This supports both EXTENDED_HISTORY (": <time>:<dur>;<cmd>") and plain lines.
"""
s = history_line.rstrip('\n')
if s.endswith('\r'):
s = s[:-1]
if ';' in s:
s = s.split(';', 1)[1]
s = s.strip()
if not s:
return False
toks = s.split()
if not toks:
return False
try:
names_env = os.environ.get('ERASE_HISTORY_SELF_NAMES', '')
if names_env:
names = set()
for x in names_env.split(','):
x = x.strip()
if x:
names.add(x)
if names and toks[0] in names:
return True
except Exception:
pass
try:
self_path = os.path.realpath(__file__)
except Exception:
return False
def _resolve_candidate(token):
"""
Resolve token to an absolute real path.
- If token contains '/', treat as a path.
- Otherwise search PATH manually (Python 3.1 compatible).
"""
try:
if '/' in token:
return os.path.realpath(os.path.expanduser(token))
path_env = os.environ.get('PATH', '')
for d in path_env.split(os.pathsep):
candidate = os.path.join(d, token)
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return os.path.realpath(candidate)
except Exception:
return None
return None
candidates = []
# Direct execution:
# erase_history.py ...
# ./erase_history.py ...
# /path/to/erase_history.py ...
candidates.append(toks[0])
# Interpreter execution:
# python erase_history.py ...
# python /path/to/erase_history.py ...
if toks[0] in ('python', 'python3'):
if len(toks) >= 2:
candidates.append(toks[1])
for c in candidates:
resolved = _resolve_candidate(c)
if resolved and resolved == self_path:
return True
return False
def erase_tail_lines(history_path, n, quiet):
"""
Remove the last n history lines from the specified history file.
The function reads the entire file, writes all but the last n lines
to a temporary file, and then atomically replaces the original file.
File permissions are preserved when possible.
Args:
history_path (str): Path to the Zsh history file.
n (int): Number of lines to remove.
Exits:
1: On read/write failure.
2: If the history file does not exist.
"""
if not os.path.exists(history_path):
print("[ERROR] History file does not exist - %s" % history_path, file=sys.stderr)
sys.exit(2)
try:
with open(history_path, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
except Exception as e:
print("[ERROR] Failed to read history file - %s (%s)" %
(history_path, str(e)), file=sys.stderr)
sys.exit(1)
total = len(lines)
if total == 0:
removed_lines = []
keep_lines = []
else:
keep_self = is_self_invocation(lines[-1])
if keep_self:
start = total - (n + 1)
end = total - 1
else:
start = total - n
end = total
if start < 0:
start = 0
if end < 0:
end = 0
removed_lines = lines[start:end]
keep_lines = lines[:start] + lines[end:]
if not quiet:
for line in removed_lines:
# Strip only the trailing newline for consistent single-line output.
# Preserve the original content as much as possible.
msg = line.rstrip('\n')
if msg.endswith('\r'):
msg = msg[:-1]
print("[INFO] Will remove line: %s" % msg)
ans = ""
try:
ans = input("Proceed with deletion? [y/yes]: ").strip().lower()
except EOFError:
ans = ""
if ans not in ("y", "yes"):
print("[INFO] Aborted")
sys.exit(1)
dir_name = os.path.dirname(history_path) or '.'
base_name = os.path.basename(history_path)
tmp_fd = None
tmp_path = None
try:
tmp_fd, tmp_path = tempfile.mkstemp(
prefix=base_name + '.', suffix='.tmp', dir=dir_name
)
with os.fdopen(tmp_fd, 'w', encoding='utf-8', errors='replace') as w:
for line in keep_lines:
w.write(line)
try:
st = os.stat(history_path)
os.chmod(tmp_path, st.st_mode)
except Exception:
pass
os.replace(tmp_path, history_path)
tmp_path = None
except Exception as e:
if tmp_fd is not None:
try:
os.close(tmp_fd)
except Exception:
pass
if tmp_path:
try:
os.unlink(tmp_path)
except Exception:
pass
print("[ERROR] Failed to update history file - %s (%s)" %
(history_path, str(e)), file=sys.stderr)
sys.exit(1)
if not quiet:
print("[INFO] Deleted")
def main():
"""
Entry point.
Parse arguments, validate input, and remove the requested number
of history lines from ~/.zsh_history (default: 1 line).
"""
n, quiet = parse_args(sys.argv[1:])
validate_n(n)
history_path = os.path.expanduser('~/.zsh_history')
erase_tail_lines(history_path, n, quiet)
return 0
if __name__ == '__main__':
if len(sys.argv) >= 2 and sys.argv[1] in ('-h', '--help', '-v', '--version'):
usage()
sys.exit(main())