##// END OF EJS Templates
`ipython history clear` subcommand
Paul Ivanov -
Show More
@@ -1,126 +1,159 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for managing IPython history.
4 4
5 5 To be invoked as the `ipython history` subcommand.
6 6 """
7 7 from __future__ import print_function
8 8
9 9 import os
10 10 import sqlite3
11 11
12 12 from IPython.config.application import Application
13 13 from IPython.core.application import BaseIPythonApplication
14 14 from IPython.utils.traitlets import Bool, Int, Dict
15 from IPython.utils.io import ask_yes_no
15 16
16 17 trim_hist_help = """Trim the IPython history database to the last 1000 entries.
17 18
18 19 This actually copies the last 1000 entries to a new database, and then replaces
19 20 the old file with the new. Use the `--keep=` argument to specify a number
20 21 other than 1000.
21 22 """
22 23
24 clear_hist_help = """Clear the IPython history database, deleting all entries.
25
26 Because this is a destructive operation, IPython will prompt the user if they
27 really want to do this. Passing a `-f` flag will force clearing without a
28 prompt.
29
30 This is an handy alias to `ipython history trim --keep=0`
31 """
32
33
23 34 class HistoryTrim(BaseIPythonApplication):
24 35 description = trim_hist_help
25 36
26 37 backup = Bool(False, config=True,
27 38 help="Keep the old history file as history.sqlite.<N>")
28 39
29 40 keep = Int(1000, config=True,
30 41 help="Number of recent lines to keep in the database.")
31 42
32 43 flags = Dict(dict(
33 44 backup = ({'HistoryTrim' : {'backup' : True}},
34 45 backup.get_metadata('help')
35 46 )
36 47 ))
37 48
38 49 aliases=Dict(dict(
39 50 keep = 'HistoryTrim.keep'
40 51 ))
41 52
42 53 def start(self):
43 54 profile_dir = self.profile_dir.location
44 55 hist_file = os.path.join(profile_dir, 'history.sqlite')
45 56 con = sqlite3.connect(hist_file)
46 57
47 58 # Grab the recent history from the current database.
48 59 inputs = list(con.execute('SELECT session, line, source, source_raw FROM '
49 60 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,)))
50 61 if len(inputs) <= self.keep:
51 62 print("There are already at most %d entries in the history database." % self.keep)
52 63 print("Not doing anything. Use --keep= argument to keep fewer entries")
53 64 return
54 65
55 66 print("Trimming history to the most recent %d entries." % self.keep)
56 67
57 68 inputs.pop() # Remove the extra element we got to check the length.
58 69 inputs.reverse()
59 70 if inputs:
60 71 first_session = inputs[0][0]
61 72 outputs = list(con.execute('SELECT session, line, output FROM '
62 73 'output_history WHERE session >= ?', (first_session,)))
63 74 sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM '
64 75 'sessions WHERE session >= ?', (first_session,)))
65 76 con.close()
66 77
67 78 # Create the new history database.
68 79 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new')
69 80 i = 0
70 81 while os.path.exists(new_hist_file):
71 82 # Make sure we don't interfere with an existing file.
72 83 i += 1
73 84 new_hist_file = os.path.join(profile_dir, 'history.sqlite.new'+str(i))
74 85 new_db = sqlite3.connect(new_hist_file)
75 86 new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
76 87 primary key autoincrement, start timestamp,
77 88 end timestamp, num_cmds integer, remark text)""")
78 89 new_db.execute("""CREATE TABLE IF NOT EXISTS history
79 90 (session integer, line integer, source text, source_raw text,
80 91 PRIMARY KEY (session, line))""")
81 92 new_db.execute("""CREATE TABLE IF NOT EXISTS output_history
82 93 (session integer, line integer, output text,
83 94 PRIMARY KEY (session, line))""")
84 95 new_db.commit()
85 96
86 97
87 98 if inputs:
88 99 with new_db:
89 100 # Add the recent history into the new database.
90 101 new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions)
91 102 new_db.executemany('insert into history values (?,?,?,?)', inputs)
92 103 new_db.executemany('insert into output_history values (?,?,?)', outputs)
93 104 new_db.close()
94 105
95 106 if self.backup:
96 107 i = 1
97 108 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
98 109 while os.path.exists(backup_hist_file):
99 110 i += 1
100 111 backup_hist_file = os.path.join(profile_dir, 'history.sqlite.old.%d' % i)
101 112 os.rename(hist_file, backup_hist_file)
102 113 print("Backed up longer history file to", backup_hist_file)
103 114 else:
104 115 os.remove(hist_file)
105 116
106 117 os.rename(new_hist_file, hist_file)
107 118
119 class HistoryClear(HistoryTrim):
120 description = clear_hist_help
121 keep = Int(0, config=False,
122 help="Number of recent lines to keep in the database.")
123
124 force = Bool(False, config=True,
125 help="Don't prompt user for confirmation")
126
127 flags = Dict(dict(
128 force = ({'HistoryClear' : {'force' : True}},
129 force.get_metadata('help')),
130 f = ({'HistoryTrim' : {'force' : True}},
131 force.get_metadata('help')
132 )
133 ))
134 aliases = Dict()
135
136 def start(self):
137 if self.force or ask_yes_no("Really delete all ipython history? ",
138 default="no", interrupt="no"):
139 HistoryTrim.start(self)
108 140
109 141 class HistoryApp(Application):
110 142 name = u'ipython-history'
111 143 description = "Manage the IPython history database."
112 144
113 145 subcommands = Dict(dict(
114 146 trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]),
147 clear = (HistoryClear, HistoryClear.description.splitlines()[0]),
115 148 ))
116 149
117 150 def start(self):
118 151 if self.subapp is None:
119 152 print("No subcommand specified. Must specify one of: %s" % \
120 153 (self.subcommands.keys()))
121 154 print()
122 155 self.print_description()
123 156 self.print_subcommands()
124 157 self.exit(1)
125 158 else:
126 159 return self.subapp.start()
General Comments 0
You need to be logged in to leave comments. Login now