Revision 50a32c37 kamaki/cli/history.py
b/kamaki/cli/history.py | ||
---|---|---|
34 | 34 |
# or implied, of GRNET S.A. |
35 | 35 |
|
36 | 36 |
import codecs |
37 |
from logging import getLogger |
|
38 |
|
|
39 |
|
|
40 |
log = getLogger(__name__) |
|
37 | 41 |
|
38 | 42 |
|
39 | 43 |
class History(object): |
... | ... | |
46 | 50 |
def __getitem__(self, cmd_ids): |
47 | 51 |
with codecs.open(self.filepath, mode='r', encoding='utf-8') as f: |
48 | 52 |
try: |
49 |
cmd_list = f.readlines()[1:] |
|
53 |
lines = f.readlines() |
|
54 |
self.counter, cmd_list = int(lines[0]), lines[1:] |
|
50 | 55 |
return cmd_list[cmd_ids] |
51 | 56 |
except IndexError: |
52 | 57 |
return None |
... | ... | |
61 | 66 |
if new_limit < 0: |
62 | 67 |
raise ValueError('Invalid history limit (%s)' % new_limit) |
63 | 68 |
old_limit, self._limit = self._limit, new_limit |
64 |
if self._limit and self._limit < old_limit:
|
|
69 |
if self._limit and ((not old_limit) or (self._limit <= old_limit)):
|
|
65 | 70 |
with codecs.open(self.filepath, mode='r', encoding='utf-8') as f: |
66 | 71 |
lines = f.readlines() |
72 |
self.counter = int(lines[0]) |
|
67 | 73 |
old_len = len(lines[1:]) |
68 |
if old_len > new_limit: |
|
69 |
self.counter += old_len - new_limit |
|
74 |
if old_len > new_limit: |
|
75 |
self.counter += old_len - new_limit |
|
76 |
with codecs.open( |
|
77 |
self.filepath, mode='w', encoding='utf-8') as f: |
|
70 | 78 |
f.write('%s\n' % self.counter) |
71 |
f.write(''.join(lines[(self.counter + 1):]))
|
|
79 |
f.write(''.join(lines[old_len - new_limit + 1:]))
|
|
72 | 80 |
f.flush() |
73 | 81 |
|
74 | 82 |
@classmethod |
... | ... | |
85 | 93 |
return r[- limit:] |
86 | 94 |
|
87 | 95 |
def add(self, line): |
96 |
line = '%s' % line or '' |
|
88 | 97 |
line = line.replace(self.token, '...') if self.token else line |
89 |
with codecs.open(self.filepath, mode='a+', encoding='utf-8') as f: |
|
90 |
f.write(line + '\n') |
|
91 |
f.flush() |
|
92 |
self.limit = self.limit |
|
98 |
try: |
|
99 |
with codecs.open(self.filepath, mode='a+', encoding='utf-8') as f: |
|
100 |
f.write(line + '\n') |
|
101 |
f.flush() |
|
102 |
self.limit = self.limit |
|
103 |
except Exception as e: |
|
104 |
log.debug('Add history failed for "%s" (%s)' % (line, e)) |
|
93 | 105 |
|
94 | 106 |
def empty(self): |
95 | 107 |
with open(self.filepath, 'w') as f: |
Also available in: Unified diff