This repository has been archived by the owner on May 9, 2020. It is now read-only.
forked from rootmos/qcd
/
qcd.py
executable file
·253 lines (189 loc) · 7.17 KB
/
qcd.py
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
#!/usr/bin/env python
# Small program for storing and retrieving paths from a database
# Copyright (C) 2014 Gustav Behm
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from optionparser import OptionParser, Command, Configuration
from os.path import expanduser, isfile, basename
from socket import gethostname
from whichdb import whichdb
from os import getcwd
from glob import glob
import shutil
import anydbm
import sys
import re
import tabularize
# Global configuration parameters
name = "qcd"
qcdCmdParser = ()
defaultDbFile = "~/." + name + "db"
dbType = ""
# Wrappers for managing the database
def mapDbFileNameForHost( filename ):
hostname = gethostname()
baseFilename = expanduser( filename + "." + hostname )
filePattern = ".*" + basename( filename )
fileGlob = expanduser( filename ) + "*"
for candidateFile in glob( fileGlob ):
if re.match(filePattern + "(\.db)?$", candidateFile):
# If either ~/.qcddb or ~/.qcddb.db has already been created (i.e.
# previous executions of qcd), then qcd will adapt this name to
# look like ~/.qcddb.<machine> or ~/.qcddb.<machine>.db
return migrateDbFileNameTo( candidateFile, baseFilename)
elif re.match(filePattern + "\." + hostname, candidateFile):
# If there is a file matching with ~/.qcddb.<current_machine>*, qcd
# will use that one.
return candidateFile
# Otherwise, qcd will try to create ~/.qcddb.<current_machine> (or
# ~/.qcddb.<current_machine>.db depending on which database anydbm
# selects).
return baseFilename
def initialize_database (writeable = False):
# Get the db file name where qcd info is/will_be stored
file = mapDbFileNameForHost( qcdCmdParser.getOption("file").value )
if not writeable and not isfile(file):
print >> sys.stderr, "Database is empty! Try adding something!"
sys.exit (1)
# changing the global dbType variable, it will contain the infomration
# retrieved from whichdb, which basically says which db implementation was
# used to create the db file.
global dbType
dbType = whichdb(file)
# Open the db
if writeable:
return anydbm.open (file, 'c')
else:
return anydbm.open (file, 'r')
def close_database (db):
db.close ()
# Helpers
def getAnonymousKey (db):
# When using anonymous entries, qcd will find out number N, that has not
# been used already as a key, to index the value in the db.
i = 1;
while True:
if not str(i) in db:
return str(i)
i += 1
def migrateDbFileNameTo(originFile, destinationFile):
if re.match("^.*(\.db)$", originFile):
# Has a db extension, so I'll add it into the destinationFile as well
destinationFile += ".db"
# Moving from originFile to destinationFile
shutil.move(originFile, destinationFile)
# Return result
return destinationFile
# Implementation of the commands
def add (syntaxError, args):
if len (args) == 0 or len (args) > 2:
syntaxError ()
db = initialize_database (True)
if len (args) == 2:
db[args[0]] = args[1]
else:
key = getAnonymousKey (db)
db[key] = args[0]
close_database (db)
def save (syntaxError, args):
if len (args) > 1:
syntaxError ()
args.append ( getcwd() )
add (syntaxError, args)
def change (syntaxError, args):
if len (args) != 2:
syntaxError ()
db = initialize_database (True)
if not args[0] in db:
print >> sys.stderr, args[0] + " does not exist in the database."
close_database (db)
sys.exit (1)
db[args[0]] = args[1]
close_database (db)
def move(syntaxError, args):
if len (args) != 2:
syntaxError ()
db = initialize_database (True)
if not args[0] in db:
print >> sys.stderr, args[0] + " does not exist in the database."
close_database (db)
sys.exit (1)
if args[1] in db:
print >> sys.stderr, args[1] + " already exist in the database."
close_database (db)
sys.exit (1)
db[args[1]] = db[args[0]]
del db[args[0]]
close_database (db)
def delete (syntaxError, args):
if len (args) != 1:
syntaxError ()
db = initialize_database (True)
try:
del db[args[0]]
except:
print >> sys.stderr, args[0] + " does not exist in the database."
close_database (db)
sys.exit (1)
close_database (db)
def list (syntaxError, args):
if len (args) != 0:
syntaxError ()
db = initialize_database ()
if dbType == "dumbdb" or dbType == "bsddb185":
tabularize.write (sorted ([(key, db[key]) for key in db.keys()]), writeable = sys.stderr)
else:
tabularize.write (sorted (db.iteritems()), writeable = sys.stderr)
close_database (db)
def get (syntaxError, args):
if len (args) != 1:
syntaxError ()
db = initialize_database ()
try:
print db[args[0]]
except:
print >> sys.stderr, args[0] + " does not exist in the database."
close_database (db)
sys.exit (1)
close_database (db)
# Setting up qcd command line interface
def createQcdCmdLineParser():
# The command line parser
cmdParser = OptionParser (name)
# The options
cmdParser.addConfiguration("f", "file", "Specifies which database to use",
defaultDbFile, syntax = "FILENAME")
# The commands
cmdParser.addCommand("h", "help", "Prints this helpful message",
lambda _,args:cmdParser.usage ())
cmdParser.addCommand("a", "add", "Add a new entry into the database",
add, syntax = "[LABEL] PATH")
cmdParser.addCommand("s", "save", "Add current path into the database",
save, syntax = "[LABEL]")
cmdParser.addCommand("m", "move", "Rename an entry in the database",
move, syntax = "FROM TO")
cmdParser.addCommand("c", "change",
"Changes the path of an entry in the database",
change, syntax = "LABEL NEW_PATH")
cmdParser.addCommand("d", "delete", "Delete an entry from the database",
delete, syntax = "LABEL")
cmdParser.addCommand("l", "list", "List the entries in the database", list)
cmdParser.addCommand("g", "get", "Retrieve an entry from the database",
get, True, syntax = "LABEL")
return cmdParser
# main
if ( __name__ == "__main__" ):
# Create a Command Line Parser
qcdCmdParser = createQcdCmdLineParser()
# Parse it!
qcdCmdParser.parse ()