Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork252
Expand file tree
/
Copy pathhistory.py
More file actions
259 lines (230 loc) · 8.65 KB
/
history.py
File metadata and controls
259 lines (230 loc) · 8.65 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
# The MIT License
#
# Copyright (c) 2009 the bpython authors.
# Copyright (c) 2012-2021 Sebastian Ramacher
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
importos
frompathlibimportPath
importstat
fromitertoolsimportislice,chain
fromtypingimportTextIO
fromcollections.abcimportIterable
from .translationsimport_
from .filelockimportFileLock
classHistory:
"""Stores readline-style history and current place in it"""
def__init__(
self,
entries:Iterable[str]|None=None,
duplicates:bool=True,
hist_size:int=100,
)->None:
ifentriesisNone:
self.entries= [""]
else:
self.entries=list(entries)
# how many lines back in history is currently selected where 0 is the
# saved typed line, 1 the prev entered line
self.index=0
# what was on the prompt before using history
self.saved_line=""
self.duplicates=duplicates
self.hist_size=hist_size
defappend(self,line:str)->None:
self.append_to(self.entries,line)
defappend_to(self,entries:list[str],line:str)->None:
line=line.rstrip("\n")
ifline:
ifnotself.duplicates:
# remove duplicates
try:
whileTrue:
entries.remove(line)
exceptValueError:
pass
entries.append(line)
deffirst(self)->str:
"""Move back to the beginning of the history."""
ifnotself.is_at_end:
self.index=len(self.entries)
returnself.entries[-self.index]
defback(
self,
start:bool=True,
search:bool=False,
target:str|None=None,
include_current:bool=False,
)->str:
"""Move one step back in the history."""
iftargetisNone:
target=self.saved_line
ifnotself.is_at_end:
ifsearch:
self.index+=self.find_partial_match_backward(
target,include_current
)
elifstart:
self.index+=self.find_match_backward(target,include_current)
else:
self.index+=1
returnself.entry
@property
defentry(self)->str:
"""The current entry, which may be the saved line"""
returnself.entries[-self.index]ifself.indexelseself.saved_line
@property
defentries_by_index(self)->list[str]:
returnlist(chain((self.saved_line,),reversed(self.entries)))
deffind_match_backward(
self,search_term:str,include_current:bool=False
)->int:
add=0ifinclude_currentelse1
start=self.index+add
foridx,valinenumerate(islice(self.entries_by_index,start,None)):
ifval.startswith(search_term):
returnidx+add
return0
deffind_partial_match_backward(
self,search_term:str,include_current:bool=False
)->int:
add=0ifinclude_currentelse1
start=self.index+add
foridx,valinenumerate(islice(self.entries_by_index,start,None)):
ifsearch_terminval:
returnidx+add
return0
defforward(
self,
start:bool=True,
search:bool=False,
target:str|None=None,
include_current:bool=False,
)->str:
"""Move one step forward in the history."""
iftargetisNone:
target=self.saved_line
ifself.index>1:
ifsearch:
self.index-=self.find_partial_match_forward(
target,include_current
)
elifstart:
self.index-=self.find_match_forward(target,include_current)
else:
self.index-=1
returnself.entry
else:
self.index=0
returnself.saved_line
deffind_match_forward(
self,search_term:str,include_current:bool=False
)->int:
add=0ifinclude_currentelse1
end=max(0,self.index- (1-add))
foridxinrange(end):
val=self.entries_by_index[end-1-idx]
ifval.startswith(search_term):
returnidx+ (0ifinclude_currentelse1)
returnself.index
deffind_partial_match_forward(
self,search_term:str,include_current:bool=False
)->int:
add=0ifinclude_currentelse1
end=max(0,self.index- (1-add))
foridxinrange(end):
val=self.entries_by_index[end-1-idx]
ifsearch_terminval:
returnidx+add
returnself.index
deflast(self)->str:
"""Move forward to the end of the history."""
ifnotself.is_at_start:
self.index=0
returnself.entries[0]
@property
defis_at_end(self)->bool:
returnself.index>=len(self.entries)orself.index==-1
@property
defis_at_start(self)->bool:
returnself.index==0
defenter(self,line:str)->None:
ifself.index==0:
self.saved_line=line
defreset(self)->None:
self.index=0
self.saved_line=""
defload(self,filename:Path,encoding:str)->None:
withopen(filename,encoding=encoding,errors="ignore")ashfile:
withFileLock(hfile,filename=str(filename)):
self.entries=self.load_from(hfile)
defload_from(self,fd:TextIO)->list[str]:
entries:list[str]= []
forlineinfd:
self.append_to(entries,line)
returnentriesiflen(entries)else [""]
defsave(self,filename:Path,encoding:str,lines:int=0)->None:
fd=os.open(
filename,
os.O_WRONLY|os.O_CREAT|os.O_TRUNC,
stat.S_IRUSR|stat.S_IWUSR,
)
withopen(fd,"w",encoding=encoding,errors="ignore")ashfile:
withFileLock(hfile,filename=str(filename)):
self.save_to(hfile,self.entries,lines)
defsave_to(
self,fd:TextIO,entries:list[str]|None=None,lines:int=0
)->None:
ifentriesisNone:
entries=self.entries
forlineinentries[-lines:]:
fd.write(line)
fd.write("\n")
defappend_reload_and_write(
self,s:str,filename:Path,encoding:str
)->None:
ifnotself.hist_size:
returnself.append(s)
try:
fd=os.open(
filename,
os.O_APPEND|os.O_RDWR|os.O_CREAT,
stat.S_IRUSR|stat.S_IWUSR,
)
withopen(fd,"a+",encoding=encoding,errors="ignore")ashfile:
withFileLock(hfile,filename=str(filename)):
# read entries
hfile.seek(0,os.SEEK_SET)
entries=self.load_from(hfile)
self.append_to(entries,s)
# write new entries
hfile.seek(0,os.SEEK_SET)
hfile.truncate()
self.save_to(hfile,entries,self.hist_size)
self.entries=entries
exceptOSErroraserr:
raiseRuntimeError(
_("Error occurred while writing to file %s (%s)")
% (filename,err.strerror)
)
else:
iflen(self.entries)==0:
# Make sure that entries contains at least one element. If the
# file and s are empty, this can occur.
self.entries= [""]