-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtcmd
executable file
·167 lines (138 loc) · 4.9 KB
/
rtcmd
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
#!/usr/bin/env python3
import argparse
import os
import sqlite3
import sys
from colorama import Style, init as colorinit
class RTCmd:
"""Wrapper class around an SQLite DB manipulation"""
DATABASE_NAME = os.path.expanduser("~/.rtcmd.db3")
def __init__(self, db=None):
"""Initialize a DB connection and create the 'commands' table
if it doesn't already exist.
"""
self._db = db if db is not None else RTCmd.DATABASE_NAME
self._conn = sqlite3.connect(self._db)
self._conn.row_factory = sqlite3.Row
self._cur = self._conn.cursor()
self._cur.execute("CREATE TABLE IF NOT EXISTS commands ("
"id INTEGER PRIMARY KEY,"
"tag TEXT NOT NULL,"
"command TEXT NOT NULL,"
"note TEXT)")
def _style_print(self, idx, string):
if idx % 2 == 0:
print(Style.BRIGHT, string, Style.RESET_ALL)
else:
print(Style.NORMAL, string, Style.RESET_ALL)
def _print_cursor(self):
"""Print the latest query results from a cursor in a human-friendly
way.
Returns
-------
int
number of processed rows
"""
rows = 0
tag = None
for row in self._cur:
rows += 1
if tag != row["tag"]:
print("{}--- {} ---".format('' if tag is None else '\n', row["tag"]))
tag = row["tag"]
self._style_print(rows, "{:5} | {}".format(row["id"], row["command"]))
if row["note"]:
self._style_print(rows, " | {}".format(row["note"]))
return rows
def add(self, tag, command, note):
"""Add a new command into the DB.
Parameters
----------
tag : str
Tag for a given command (e.g. 'git')
command : str
Command to store (e.g. 'git commit')
note : str
Optional note (e.g. 'Commit changes')
"""
self._cur.execute("INSERT INTO commands (tag, command, note) "
"VALUES(?, ?, ?)", (tag, command, note))
def list(self, tag=None):
"""List stored commands.
Parameters
----------
tag : str
If specified, list only commands with this tag
"""
if tag is not None:
self._cur.execute("SELECT * FROM commands WHERE tag = ? "
"ORDER BY tag", (tag,))
else:
self._cur.execute("SELECT * FROM commands ORDER BY tag")
rows = self._print_cursor()
if rows == 0:
print("Nothing to show")
def remove(self, index):
"""Remove a command with given index.
Parameters
----------
index : int
Absolute record index (i.e. index used in the DB)
"""
self._cur.execute("DELETE FROM commands WHERE id = ?", (index,))
def search(self, term):
"""Search for commands corresponding to given term.
Parameters
----------
term : str
Term to search for (using SQL syntax)
"""
self._cur.execute("SELECT * FROM commands WHERE command LIKE ? "
"OR note LIKE ?", (term, term))
rows = self._print_cursor()
if rows == 0:
print("Nothing was found")
def __del__(self):
"""Commit all changes and close the DB connection."""
self._conn.commit()
self._conn.close()
if __name__ == "__main__":
colorinit()
parser = argparse.ArgumentParser()
parser.add_argument("--command",
help="command to remember")
parser.add_argument("--database",
help="Path to a custom DB")
parser.add_argument("--delete", metavar="IDX",
help="delete a saved command with a given index")
parser.add_argument("--list", metavar="TAG", nargs="?", const="",
help="list saved commands")
parser.add_argument("--note",
help="optional note")
parser.add_argument("--search", metavar="TERM",
help="Search in 'command' and 'note' fields (?, %% - wildcards)")
parser.add_argument("--tag",
help="tag for the given command")
args = parser.parse_args()
rtcmd = RTCmd(args.database)
try:
# ADD
if args.tag and args.command:
rtcmd.add(args.tag, args.command, args.note)
# DELETE
elif args.delete:
rtcmd.remove(args.delete)
# LIST
elif args.list is not None:
if len(args.list) == 0:
args.list = None
rtcmd.list(args.list)
elif args.search:
rtcmd.search(args.search)
# INVALID ARGUMENTS
else:
parser.print_help()
sys.exit(1)
except Exception as e:
print("Error: {}".format(e), file=sys.stderr)
sys.exit(1)