From: <Z3...@us...> - 2012-09-24 21:12:28
|
Revision: 343 http://spd.svn.sourceforge.net/spd/?rev=343&view=rev Author: Z3po Date: 2012-09-24 21:12:21 +0000 (Mon, 24 Sep 2012) Log Message: ----------- got the whole thing back working. Implemented devel storage module. For now thats perfect for getting everything implemented. We can change the storage to gpg or/and gpg with svn afterwards. Modified Paths: -------------- branches/spd-ng/src/spdConfig.py branches/spd-ng/src/spdCore.py branches/spd-ng/src/spdInterface.py branches/spd-ng/src/spdInterfaces/__init__.py branches/spd-ng/src/spdInterfaces/cli.py branches/spd-ng/src/spdStore/__init__.py branches/spd-ng/src/spdStore/devel.py branches/spd-ng/src/spdStore/plain.py branches/spd-ng/src/test.db Added Paths: ----------- branches/spd-ng/src/spdInterfaces/ Removed Paths: ------------- branches/spd-ng/src/Interfaces/ Modified: branches/spd-ng/src/spdConfig.py =================================================================== --- branches/spd-ng/src/spdConfig.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdConfig.py 2012-09-24 21:12:21 UTC (rev 343) @@ -7,352 +7,352 @@ __version__ = '0.3-alpha' class Config(object): # {{{ - '''This is the Configuration Module - You can read or set config options''' - __configfile = None + '''This is the Configuration Module + You can read or set config options''' + __configfile = None - ReturnCodes = { 2 : 'Missing ConfigFile', - 4 : 'ConfigFile not Readable', - 8 : 'ConfigFile not Writeable', - 16 : 'Configfile Writeable but another Error Occured', - 32 : 'Section not found', - 64 : 'Option not found' } - ConfigSection = 'Main' + ReturnCodes = { 2 : 'Missing ConfigFile', + 4 : 'ConfigFile not Readable', + 8 : 'ConfigFile not Writeable', + 16 : 'Configfile Writeable but another Error Occured', + 32 : 'Section not found', + 64 : 'Option not found' } + ConfigSection = 'Main' - def __init__(self, configfile='~/.spd/config'): # {{{ - self.__configfile = os.path.expanduser(configfile) - # }}} + def __init__(self, configfile='~/.spd/config'): # {{{ + self.__configfile = os.path.expanduser(configfile) + # }}} - def __ErrorHandler(self,message): # {{{ - """ErrorHandler of the Config Module. - # message: means the \'Exception\' to throw""" - print "################################################" - print "spdConfig ErrorHandler." - print "Configfile: " + self.__configfile - print "ERRORMESSAGE: " + message - print "################################################" - exit(2) - # }}} + def __ErrorHandler(self,message): # {{{ + """ErrorHandler of the Config Module. + # message: means the \'Exception\' to throw""" + print "################################################" + print "spdConfig ErrorHandler." + print "Configfile: " + self.__configfile + print "ERRORMESSAGE: " + message + print "################################################" + exit(2) + # }}} - def __checkConfigFileExist(self): # {{{ - """Does the Config file exist?""" + def __checkConfigFileExist(self): # {{{ + """Does the Config file exist?""" - if os.access(self.__configfile, os.F_OK): - return 0 - else: - return 2 - # }}} + if os.access(self.__configfile, os.F_OK): + return 0 + else: + return 2 + # }}} - def __checkConfigFileReadable(self): # {{{ - """Is the Config file readable?""" + def __checkConfigFileReadable(self): # {{{ + """Is the Config file readable?""" - reval = self.__checkConfigFileExist() - config = RawConfigParser() + reval = self.__checkConfigFileExist() + config = RawConfigParser() - if reval > 0: - return reval, config + if reval > 0: + return reval, config - if os.access(self.__configfile,os.R_OK): - config.read(self.__configfile) - return 0,config - else: - return 4, config - # }}} + if os.access(self.__configfile,os.R_OK): + config.read(self.__configfile) + return 0,config + else: + return 4, config + # }}} - def __checkConfigFileWriteable(self): # {{{ - """Is the Config file writeable?""" + def __checkConfigFileWriteable(self): # {{{ + """Is the Config file writeable?""" - reval = self.__checkConfigFileExist() + reval = self.__checkConfigFileExist() - if reval > 0: - try: - configfile = open(self.__configfile, 'wb') - except IOError: - return 8, configfile - else: - return 0, configfile + if reval > 0: + try: + configfile = open(self.__configfile, 'wb') + except IOError: + return 8, configfile + else: + return 0, configfile - if os.access(self.__configfile,os.W_OK): - configfile = open(self.__configfile, 'wb') - else: - return 8, None + if os.access(self.__configfile,os.W_OK): + configfile = open(self.__configfile, 'wb') + else: + return 8, None - return 0, configfile - # }}} + return 0, configfile + # }}} - def __writeConfigFile(self,config): # {{{ - '''Write the Config given. - # config: the configobject.''' + def __writeConfigFile(self,config): # {{{ + '''Write the Config given. + # config: the configobject.''' - reval, configfile = self.__checkConfigFileWriteable() - if reval > 0: - return reval + reval, configfile = self.__checkConfigFileWriteable() + if reval > 0: + return reval - try: - config.write(configfile) - except Exception, e: - return 16 - # }}} + try: + config.write(configfile) + except Exception, e: + return 16 + # }}} - def __hasSection(self,section): # {{{ - """Check if a given section exists. - # section: the given section.""" + def __hasSection(self,section): # {{{ + """Check if a given section exists. + # section: the given section.""" - reval, config = self.__checkConfigFileReadable() - if reval > 0: - return reval, config + reval, config = self.__checkConfigFileReadable() + if reval > 0: + return reval, config - if config.has_section(section): - return 0, config + if config.has_section(section): + return 0, config - return 32, config - # }}} + return 32, config + # }}} - def __addSection(self,section): # {{{ - """create a section if its not in configfile. - # section: the section to create.""" + def __addSection(self,section): # {{{ + """create a section if its not in configfile. + # section: the section to create.""" - reval, config = self.__hasSection(section) + reval, config = self.__hasSection(section) - if reval > 0 and reval < 32 and reval is not 2: - return reval + if reval > 0 and reval < 32 and reval is not 2: + return reval - config.add_section(section) - reval = self.__writeConfigFile(config) - - if reval > 0: - return reval + config.add_section(section) + reval = self.__writeConfigFile(config) + + if reval > 0: + return reval - return 0 - # }}} + return 0 + # }}} - def __delSection(self,section): # {{{ - """delete a Section from configfile. - # section: the section to delete.""" + def __delSection(self,section): # {{{ + """delete a Section from configfile. + # section: the section to delete.""" - reval, config = self.__hasSection(section) - - if reval > 0 and reval < 32: - return reval + reval, config = self.__hasSection(section) + + if reval > 0 and reval < 32: + return reval - config.remove_section(section) - reval = self.__writeConfigFile(config) + config.remove_section(section) + reval = self.__writeConfigFile(config) - if reval > 0: - return reval + if reval > 0: + return reval - return 0 - # }}} + return 0 + # }}} - def __getOption(self,section,option): # {{{ - """Return the option from section. - # section: in which section is the option configured? - # option: option to return.""" + def __getOption(self,section,option): # {{{ + """Return the option from section. + # section: in which section is the option configured? + # option: option to return.""" - reval, config = self.__hasSection(section) + reval, config = self.__hasSection(section) - if reval > 0: - return reval, None + if reval > 0: + return reval, None - if config.has_option(section,option): - return 0, config.get(section,option) - else: - return 64, None - # }}} + if config.has_option(section,option): + return 0, config.get(section,option) + else: + return 64, None + # }}} - def __setOption(self,section,option,value): # {{{ - """Create or set the given option. - # section: section of the option. - # option: option to set/change. - # value: set the option to this value.""" + def __setOption(self,section,option,value): # {{{ + """Create or set the given option. + # section: section of the option. + # option: option to set/change. + # value: set the option to this value.""" - reval, config = self.__hasSection(section) - - if reval > 0: - return reval + reval, config = self.__hasSection(section) + + if reval > 0: + return reval - config.set(section,option,value) - reval = self.__writeConfigFile(config) + config.set(section,option,value) + reval = self.__writeConfigFile(config) - if reval > 0: - return reval + if reval > 0: + return reval - return 0 - # }}} + return 0 + # }}} - def __delOption(self,section,option): # {{{ - """delete an option. - # section: which section holds the option? - # option: option to delete.""" + def __delOption(self,section,option): # {{{ + """delete an option. + # section: which section holds the option? + # option: option to delete.""" - reval, config = self.__hasSection(section) + reval, config = self.__hasSection(section) - if reval > 0: - return reval + if reval > 0: + return reval - reval, option = self.__getOption(section,option) + reval, option = self.__getOption(section,option) - if reval > 0: - return reval + if reval > 0: + return reval - config.remove_option(section,option) - reval = self.__writeConfigFile(config) + config.remove_option(section,option) + reval = self.__writeConfigFile(config) - if reval > 0: - return reval + if reval > 0: + return reval - return 0 - # }}} + return 0 + # }}} - def getAllSections(self): # {{{ - reval, config = self.__checkConfigFileReadable() - if reval > 0: - return reval, config + def getAllSections(self): # {{{ + reval, config = self.__checkConfigFileReadable() + if reval > 0: + return reval, config - if config.sections(): - return 0, config.sections() + if config.sections(): + return 0, config.sections() - return 32, config - # }}} + return 32, config + # }}} - def getSections(self, raw=False): # {{{ - """Return all sections from configfile.""" + def getSections(self, raw=False): # {{{ + """Return all sections from configfile.""" - reval, config = self.__checkConfigFileReadable() + reval, config = self.__checkConfigFileReadable() - if reval > 0: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0: + self.__ErrorHandler(self.ReturnCodes[reval]) - if raw: - return 0, config.sections() + if raw: + return 0, config.sections() - return config.sections() - - # }}} + return config.sections() + + # }}} - def addConfigSection(self,section): # {{{ - reval = self.__addSection(section) + def addConfigSection(self,section): # {{{ + reval = self.__addSection(section) - if reval > 0: - self.__ErrorHandler(self.ReturnCodes[reval]) - # }}} + if reval > 0: + self.__ErrorHandler(self.ReturnCodes[reval]) + # }}} - def getConfigVersion(self, raw=False): # {{{ - """Return the config version.""" + def getConfigVersion(self, raw=False): # {{{ + """Return the config version.""" - reval, option = self.__getOption("Main","version") + reval, option = self.__getOption("Main","version") - if reval > 2 and reval < 32: - self.__ErrorHandler(self.ReturnCodes[reval]) # don't tolerate These + if reval > 2 and reval < 32: + self.__ErrorHandler(self.ReturnCodes[reval]) # don't tolerate These - if reval > 0: - if raw: - return reval, None + if reval > 0: + if raw: + return reval, None - self.__ErrorHandler(self.ReturnCodes[reval]) - - if raw: - return reval, option + self.__ErrorHandler(self.ReturnCodes[reval]) + + if raw: + return reval, option - return option - # }}} + return option + # }}} - def setConfigVersion(self,version): # {{{ - """set the config version to the given version. - # version: version number.""" + def setConfigVersion(self,version): # {{{ + """set the config version to the given version. + # version: version number.""" - reval = self.__setOption("Main","version",version) - - if reval > 0: - self.__ErrorHandler(self.ReturnCodes[reval]) - # }}} + reval = self.__setOption("Main","version",version) + + if reval > 0: + self.__ErrorHandler(self.ReturnCodes[reval]) + # }}} - def getClientmode(self, raw=False): # {{{ - '''get the clientmode. - # return the clientmode option''' + def getClientmode(self, raw=False): # {{{ + '''get the clientmode. + # return the clientmode option''' - reval, clientmode = self.__getOption('Main', 'clientmode') + reval, clientmode = self.__getOption('Main', 'clientmode') - if reval > 0 and reval < 64: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0 and reval < 64: + self.__ErrorHandler(self.ReturnCodes[reval]) - if reval > 0: - if raw: - return reval, None - else: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0: + if raw: + return reval, None + else: + self.__ErrorHandler(self.ReturnCodes[reval]) - if raw: - return reval, clientmode + if raw: + return reval, clientmode - return clientmode - # }}} + return clientmode + # }}} - def setClientmode(self,clientmode): # {{{ - """set the clientmode. - # clientmode: clientmode to use.""" + def setClientmode(self,clientmode): # {{{ + """set the clientmode. + # clientmode: clientmode to use.""" - reval = self.__setOption("Main","clientmode",clientmode) - - if reval > 0: - self.__ErrorHandler(self.ReturnCodes[reval]) - # }}} + reval = self.__setOption("Main","clientmode",clientmode) + + if reval > 0: + self.__ErrorHandler(self.ReturnCodes[reval]) + # }}} - def getPasswordfield(self, raw=False): # {{{ - '''get the clientmode. - # return the Password Column''' + def getPasswordfield(self, raw=False): # {{{ + '''get the clientmode. + # return the Password Column''' - reval, clientmode = self.__getOption('Main', 'passwordfield') + reval, clientmode = self.__getOption('Main', 'passwordfield') - if reval > 0 and reval < 64: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0 and reval < 64: + self.__ErrorHandler(self.ReturnCodes[reval]) - if reval > 0: - if raw: - return reval, None - else: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0: + if raw: + return reval, None + else: + self.__ErrorHandler(self.ReturnCodes[reval]) - if raw: - return reval, clientmode + if raw: + return reval, clientmode - return clientmode - # }}} + return clientmode + # }}} - def setPasswordfield(self,passcolumn): # {{{ - """set the Password Column. - # passcolumn: passcolumn to set.""" + def setPasswordfield(self,passcolumn): # {{{ + """set the Password Column. + # passcolumn: passcolumn to set.""" - reval = self.__setOption("Main","passwordfield",passcolumn) - - if reval > 0: - self.__ErrorHandler(self.ReturnCodes[reval]) - # }}} + reval = self.__setOption("Main","passwordfield",passcolumn) + + if reval > 0: + self.__ErrorHandler(self.ReturnCodes[reval]) + # }}} - def getStoreType(self, raw=False): # {{{ - '''get the clientmode. - # return the clientmode option''' + def getStoreType(self, raw=False): # {{{ + '''get the clientmode. + # return the clientmode option''' - reval, storetype = self.__getOption('Main', 'storetype') + reval, storetype = self.__getOption('Main', 'storetype') - if reval > 0 and reval < 64: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0 and reval < 64: + self.__ErrorHandler(self.ReturnCodes[reval]) - if reval > 0: - if raw: - return reval, None - else: - self.__ErrorHandler(self.ReturnCodes[reval]) + if reval > 0: + if raw: + return reval, None + else: + self.__ErrorHandler(self.ReturnCodes[reval]) - if raw: - return reval, storetype + if raw: + return reval, storetype - return storetype - # }}} + return storetype + # }}} # }}} # EOF -# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3 +# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4 Modified: branches/spd-ng/src/spdCore.py =================================================================== --- branches/spd-ng/src/spdCore.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdCore.py 2012-09-24 21:12:21 UTC (rev 343) @@ -1,11 +1,10 @@ '''spdCore Module. - Handles the Datastore of SPD. - Usage: - import spdCore - coreobject = spdCore.Core()''' +Handles the Datastore of SPD. +Usage: +import spdCore +coreobject = spdCore.Core()''' -import sqlite3 import re import random import string @@ -13,180 +12,179 @@ class Core(object): - # create the database from the stuff out of the store - def __init__(self,ConfigObject): # {{{ - self.ConfigSection = ConfigObject.ConfigSection - self.PasswordColumn = ConfigObject.getPasswordfield() - self.storeType = __import__('spdStore.' + ConfigObject.getStoreType()) - self.db = sqlite3.connect(':memory:') - self.db.row_factory = self.__sql2dict - self.dbc = self.db.cursor() + # create the database from the stuff out of the store + def __init__(self,ConfigObject): # {{{ + self.ConfigSection = ConfigObject.ConfigSection + self.PasswordColumn = ConfigObject.getPasswordfield() + self.spdStore = __import__('spdStore.' + ConfigObject.getStoreType(), fromlist=['',]) + self.db = self.spdStore.getData() + self.db.row_factory = self.__sql2dict + self.dbc = self.db.cursor() - self.deletedColumns = [] - # }}} + self.deletedColumns = [] + # }}} - def __ErrorHandler(self,function,message): # {{{ - """ErrorHandler of the Core Module. - # function: the function which throws the error - # message: means the \'Exception\' to throw""" - print "################################################" - print "spdCore ErrorHandler." - print "ERRORFUNCTION: " + function - print "ERRORMESSAGE: " + message - print "################################################" - exit(2) - # }}} + def __ErrorHandler(self,function,message): # {{{ + """ErrorHandler of the Core Module. + # function: the function which throws the error + # message: means the \'Exception\' to throw""" + print "################################################" + print "spdCore ErrorHandler." + print "ERRORFUNCTION: " + function + print "ERRORMESSAGE: " + message + print "################################################" + exit(2) + # }}} - def __sql2dict(self,cursor,row): # {{{ - result = {} - for ColumnNr, Column in enumerate(cursor.description): - result[Column[0]] = row[ColumnNr] + def __sql2dict(self,cursor,row): # {{{ + result = {} + for ColumnNr, Column in enumerate(cursor.description): + result[Column[0]] = row[ColumnNr] - return result + return result - # }}} + # }}} - def searchEntry(self,SearchList,byid=False): # {{{ + def searchEntry(self,SearchList,byid=False): # {{{ - query = 'select * from ' + self.ConfigSection + ' where ' + query = 'select * from ' + self.ConfigSection + ' where ' - if byid: - for __id in SearchList: - if re.match('\d+',__id): - query += '__ID = ' + __id + ' or ' - else: - self.__ErrorHandler('searchEntry', 'Searching for ID but no valid ID given: ' + __id) - query = query[0:-3] + # search by ID + if byid: + for __id in SearchList: + if re.match('\d+',__id): + query += '__ID = ' + __id + ' or ' + else: + self.__ErrorHandler('searchEntry', 'Searching for ID but no valid ID given: ' + __id) + query = query[0:-3] + else: + # Build the where-clause + for pattern in SearchList: + query += '(' - else: - # Build the where-clause - for pattern in SearchList: - query += '(' + for i in self.getColumns(): + if i != self.PasswordColumn: + query += i + " like '%" + pattern + "%' or " + query = query[0:-4] + ') and ' + query = query[0:-5] - for i in self.getColumns(): - if i != self.PasswordColumn: - query += i + " like '%" + pattern + "%' or " + # Execute the query + self.dbc.execute(query) - query = query[0:-4] + ') and ' - query = query[0:-5] + result = {} + for i in self.dbc: + for j in i: + try: + result[j].append(i[j]) + except KeyError: + result[j] = [i[j]] + + return result + # }}} + + def addEntry(self,NewDict): # {{{ + query = 'insert into ' + self.ConfigSection + '( ' + + cols = '' + vals = '' + for i in NewDict.keys(): + cols += i + ', ' + vals += ':' + i + ', ' - # Execute the query - self.dbc.execute(query) + query += cols[0:-2] + ') VALUES ( ' + vals[0:-2] + ')' + self.dbc.execute(query,NewDict) + self.db.commit() + # }}} - result = {} - for i in self.dbc: - for j in i: - try: - result[j].append(i[j]) - except KeyError: - result[j] = [i[j]] - - return result - # }}} - - def addEntry(self,NewDict): # {{{ - query = 'insert into ' + self.ConfigSection + '( ' - - cols = '' - vals = '' - for i in NewDict.keys(): - cols += i + ', ' - vals += ':' + i + ', ' + def delEntry(self,ID): # {{{ + for __id in ID: + query = 'delete from '+ self.ConfigSection +' where __ID=\'' + str(__id) + '\'' + self.dbc.execute(query) - query += cols[0:-2] + ') VALUES ( ' + vals[0:-2] + ')' - self.dbc.execute(query,NewDict) - self.db.commit() - # }}} + self.db.commit() + # }}} - def delEntry(self,ID): # {{{ - for __id in ID: - query = 'delete from '+ self.ConfigSection +' where __ID=\'' + str(__id) + '\'' - self.dbc.execute(query) + def editEntry(self,__passdict): # {{{ + query = 'UPDATE ' + self.ConfigSection + ' SET ' + for i in range(0, len(__passdict['__ID'])): + for __column in __passdict: + if __column != '__ID': + query += __column + ' = \'' + __passdict[__column][i] + '\', ' + query = query[0:-2] + query += ' WHERE __ID = ' + str(__passdict['__ID'][i]) + self.dbc.execute(query) + query = 'UPDATE ' + self.ConfigSection + ' SET ' + self.db.commit() + # }}} - self.db.commit() - # }}} + def getColumns(self,showid=True): # {{{ + query = "pragma Table_info('" + self.ConfigSection + "')" + self.dbc.execute(query) - def editEntry(self,__passdict): # {{{ - query = 'UPDATE ' + self.ConfigSection + ' SET ' - for i in range(0, len(__passdict['__ID'])): - for __column in __passdict: - if __column != '__ID': - query += __column + ' = \'' + __passdict[__column][i] + '\', ' - query = query[0:-2] - query += ' WHERE __ID = ' + str(__passdict['__ID'][i]) - self.dbc.execute(query) - query = 'UPDATE ' + self.ConfigSection + ' SET ' - self.db.commit() - # }}} + result = [] + for i in self.dbc: + if not showid and i['name'] == "__ID": + continue + if i['name'] not in self.deletedColumns: + result.append(i['name']) + return result + # }}} - def getColumns(self,showid=True): # {{{ - query = "pragma Table_info('" + self.ConfigSection + "')" - self.dbc.execute(query) + def addColumn(self,columnname): # {{{ + if columnname in self.getColumns(showid=True): + self.__ErrorHandler('addColumn','Column \"' + columnname + '\" already exists') + query='alter table ' + self.ConfigSection + ' add column ' + columnname + ' text ' + self.db.execute(query) + self.db.commit() + # }}} + + def delColumn(self,columnname): # {{{ + __columns = '' + __newcolumns = '' + for __column in self.getColumns(showid=True): + if __column == columnname and columnname != '__ID': + continue - result = [] - for i in self.dbc: - if not showid and i['name'] == "__ID": - continue - if i['name'] not in self.deletedColumns: - result.append(i['name']) - return result - # }}} + if __column == '__ID': + __newcolumn = __column + ' INTEGER PRIMARY KEY' + else: + __newcolumn = __column + ' text' - def addColumn(self,columnname): # {{{ - if columnname in self.getColumns(showid=True): - self.__ErrorHandler('addColumn','Column \"' + columnname + '\" already exists') - query='alter table ' + self.ConfigSection + ' add column ' + columnname + ' text ' - self.db.execute(query) - self.db.commit() - # }}} - - def delColumn(self,columnname): # {{{ - __columns = '' - __newcolumns = '' - for __column in self.getColumns(showid=True): - if __column == columnname and columnname != '__ID': - continue + if __newcolumns == '': + __newcolumns = __newcolumn + else: + __newcolumns = __newcolumns + ',' + __newcolumn - if __column == '__ID': - __newcolumn = __column + ' INTEGER PRIMARY KEY' - else: - __newcolumn = __column + ' text' + if __columns == '': + __columns = __column + else: + __columns = __columns + ',' + __column - if __newcolumns == '': - __newcolumns = __newcolumn - else: - __newcolumns = __newcolumns + ',' + __newcolumn + # it's not that easy, to delete a column in SQLite + self.dbc.executescript(""" + CREATE TEMPORARY TABLE """ + self.ConfigSection + """_backup(""" + __newcolumns + """); + INSERT INTO """ + self.ConfigSection + """_backup SELECT """ + __columns + """ FROM """ + self.ConfigSection + """; + DROP TABLE """ + self.ConfigSection + """; + CREATE TABLE """ + self.ConfigSection + """(""" + __newcolumns + """); + INSERT INTO """ + self.ConfigSection + """ SELECT """ + __columns + """ FROM """ + self.ConfigSection + """_backup; + DROP TABLE """ + self.ConfigSection + """_backup; + """) + self.db.commit() + # }}}a + + def makepass(self,size=16): # {{{ + chars = [] + chars.extend([i for i in string.ascii_letters]) + chars.extend([i for i in string.digits]) + chars.extend([i for i in '\'"!@#$%&*()-_=+[{}]~^,<.>;:/?']) + + passwd = '' + + for i in range(size): + passwd += random.choice(chars) + + return passwd + # }}} - if __columns == '': - __columns = __column - else: - __columns = __columns + ',' + __column - - # it's not that easy, to delete a column in SQLite - self.dbc.executescript(""" - CREATE TEMPORARY TABLE """ + self.ConfigSection + """_backup(""" + __newcolumns + """); - INSERT INTO """ + self.ConfigSection + """_backup SELECT """ + __columns + """ FROM """ + self.ConfigSection + """; - DROP TABLE """ + self.ConfigSection + """; - CREATE TABLE """ + self.ConfigSection + """(""" + __newcolumns + """); - INSERT INTO """ + self.ConfigSection + """ SELECT """ + __columns + """ FROM """ + self.ConfigSection + """_backup; - DROP TABLE """ + self.ConfigSection + """_backup; - """) - self.db.commit() - # }}}a - - def makepass(self,size=16): # {{{ - chars = [] - chars.extend([i for i in string.ascii_letters]) - chars.extend([i for i in string.digits]) - chars.extend([i for i in '\'"!@#$%&*()-_=+[{}]~^,<.>;:/?']) - - passwd = '' - - for i in range(size): - passwd += random.choice(chars) - - return passwd - # }}} - # EOF -# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3 +# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4 Modified: branches/spd-ng/src/spdInterface.py =================================================================== --- branches/spd-ng/src/spdInterface.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdInterface.py 2012-09-24 21:12:21 UTC (rev 343) @@ -10,7 +10,7 @@ Interface = spdInterface.Interface('CLI') if building your own interface, name it "whatever" and pass "whatever" -to the Interface Class. The Module must be in spds Interfaces path.''' +to the Interface Class. The Module must be in spds spdInterfaces path.''' from sys import exit import os @@ -35,28 +35,28 @@ if not os.access(self.__spddir, os.F_OK): os.mkdir(self.__spddir) - __config = spdConfig.Config() + self.ConfigObject = spdConfig.Config() - reval, initcheck['version'] = __config.getConfigVersion(raw=True) + reval, initcheck['version'] = self.ConfigObject.getConfigVersion(raw=True) if reval > 0 and reval < 64: - spdDefaults.createDefaultConfig(__config) + spdDefaults.createDefaultConfig(self.ConfigObject) return self.__startupCheck() elif reval == 64: print 'ConfigVersion not found...setting Default one\n' - __input = raw_input('Press any key') - __config.setConfigVersion('0.3-alpha') - initcheck.update({ 'version' : __config.getConfigVersion() }) + __blackhole = raw_input('Press any key') + self.ConfigObject.setConfigVersion('0.3-alpha') + initcheck.update({ 'version' : self.ConfigObject.getConfigVersion() }) - reval, initcheck['clientmode'] = __config.getClientmode(raw=True) + reval, initcheck['clientmode'] = self.ConfigObject.getClientmode(raw=True) if reval > 0: print 'Clientmode not found...setting it to CLI\n' - __input = raw_input('Press any key') - __config.setClientmode('cli') - initcheck.update({ 'clientmode' : __config.getClientmode() }) + __blackhole = raw_input('Press any key') + self.ConfigObject.setClientmode('cli') + initcheck.update({ 'clientmode' : self.ConfigObject.getClientmode() }) - reval, __passwordfield = __config.getPasswordfield(raw=True) + reval, __passwordfield = self.ConfigObject.getPasswordfield(raw=True) if reval == 0: initcheck.update({ 'passwordfield' : __passwordfield }) @@ -64,15 +64,15 @@ if not clientmode: clientmode = initcheck['clientmode'] - __tempclient = __import__('Interfaces.' + clientmode.lower()) - self.__client = __tempclient.cli + __tempclient = __import__('spdInterfaces.' + clientmode.lower(), fromlist=['',]) + self.__client = __tempclient del __tempclient if 'passwordfield' in initcheck: self.__client._passwordfield = initcheck['passwordfield'] - self.__core = spdCore.Core(__config) + self.__core = spdCore.Core(self.ConfigObject) self.__version = { 'ConfigFile' : initcheck['version'], 'spdInterface' : __version__, Modified: branches/spd-ng/src/spdInterfaces/__init__.py =================================================================== --- branches/spd-ng/src/Interfaces/__init__.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdInterfaces/__init__.py 2012-09-24 21:12:21 UTC (rev 343) @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +'''spdInterfaces Module + +This Module takes Care of the Interface used by SPD.''' Modified: branches/spd-ng/src/spdInterfaces/cli.py =================================================================== --- branches/spd-ng/src/Interfaces/cli.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdInterfaces/cli.py 2012-09-24 21:12:21 UTC (rev 343) @@ -12,257 +12,257 @@ passwordfield = 'Password' def __ErrorHandler(function,message): # {{{ - """ErrorHandler of the Client Module. - # function: the function which throws the error - # message: means the \'Exception\' to throw""" - print "################################################" - print "Cli ErrorHandler." - print "ERRORFUNCTION: " + function - print "ERRORMESSAGE: " + message - print "################################################" - exit(2) + """ErrorHandler of the Client Module. + # function: the function which throws the error + # message: means the \'Exception\' to throw""" + print "################################################" + print "Cli ErrorHandler." + print "ERRORFUNCTION: " + function + print "ERRORMESSAGE: " + message + print "################################################" + exit(2) # }}} def printPasswords(passdict,args=None): # {{{ - """Print the passwords out of a dictionary. - # passdict: the dictionary full of passwords""" - __keylength = {} - pwonly = False + """Print the passwords out of a dictionary. + # passdict: the dictionary full of passwords""" + __keylength = {} + pwonly = False - if args is not None: - if 'pwonly' in args: - pwonly = args['pwonly'] - if 'outmode' in args: - __outmode = args['outmode'] + if args is not None: + if 'pwonly' in args: + pwonly = args['pwonly'] + if 'outmode' in args: + __outmode = args['outmode'] - if type(passdict).__name__ != 'NoneType' and len(passdict) != 0: - if pwonly: - if len(passdict['__ID']) > 1: - __ErrorHandler('printPasswords', 'pwonly selected but more than one result returned') - else: - print passdict[passwordfield][0] + if type(passdict).__name__ != 'NoneType' and len(passdict) != 0: + if pwonly: + if len(passdict['__ID']) > 1: + __ErrorHandler('printPasswords', 'pwonly selected but more than one result returned') + else: + print passdict[passwordfield][0] - elif __outmode == 'line': - length = 0 - for key in passdict.keys(): - if length < len(key): - length = len(key) - print "" - for i in range(0,len(passdict.values()[0])): - print "__ID".ljust(length) + ':' + str(passdict["__ID"][i]) - for key in passdict: - if key == '__ID': - continue - if type(passdict[key][i]).__name__ != 'NoneType': - print key.ljust(length) + ': ' + sub('\n','\n ' + ' '.ljust(length),passdict[key][i]) - else: - print key.ljust(length) + ': ' - print "" - elif __outmode == 'wide': - for key in passdict: - __keylength.update({ key : 0 }) + elif __outmode == 'line': + length = 0 + for key in passdict.keys(): + if length < len(key): + length = len(key) + print "" + for i in range(0,len(passdict.values()[0])): + print "__ID".ljust(length) + ':' + str(passdict["__ID"][i]) + for key in passdict: + if key == '__ID': + continue + if type(passdict[key][i]).__name__ != 'NoneType': + print key.ljust(length) + ': ' + sub('\n','\n ' + ' '.ljust(length),passdict[key][i]) + else: + print key.ljust(length) + ': ' + print "" + elif __outmode == 'wide': + for key in passdict: + __keylength.update({ key : 0 }) - if len(key) > __keylength[key]: - __keylength[key] = len(key) - for value in passdict[key]: - if value is not None: - if search('\n',str(value)): - for partvalue in value.split('\n'): - if len(str(partvalue)) > __keylength[key]: - __keylength[key] = len(str(partvalue)) - else: - if len(str(value)) > __keylength[key]: - __keylength[key] = len(str(value)) + if len(key) > __keylength[key]: + __keylength[key] = len(key) + for value in passdict[key]: + if value is not None: + if search('\n',str(value)): + for partvalue in value.split('\n'): + if len(str(partvalue)) > __keylength[key]: + __keylength[key] = len(str(partvalue)) + else: + if len(str(value)) > __keylength[key]: + __keylength[key] = len(str(value)) - for key in passdict: - stdout.write(key.ljust(__keylength[key]) + '|') - stdout.write('\n') + for key in passdict: + stdout.write(key.ljust(__keylength[key]) + '|') + stdout.write('\n') - __entries = len(passdict.values()[0]) + __entries = len(passdict.values()[0]) - for i in range(0,__entries): - __space = '' - for key in passdict: - if passdict[key][i] is None: - passdict[key][i] = '' - __count = 0 - for line in str(passdict[key][i]).split('\n'): - if __count > 0: - stdout.write('\n' + __space) - stdout.write(line.ljust(__keylength[key]) + '|') - __count += 1 - __space = __space + ''.ljust(__keylength[key],'>') + '>' - stdout.write('\n') - else: - __ErrorHandler('printPasswords', 'output mode unknown: ' + str(__outmode)) - else: - print "No Results found" + for i in range(0,__entries): + __space = '' + for key in passdict: + if passdict[key][i] is None: + passdict[key][i] = '' + __count = 0 + for line in str(passdict[key][i]).split('\n'): + if __count > 0: + stdout.write('\n' + __space) + stdout.write(line.ljust(__keylength[key]) + '|') + __count += 1 + __space = __space + ''.ljust(__keylength[key],'>') + '>' + stdout.write('\n') + else: + __ErrorHandler('printPasswords', 'output mode unknown: ' + str(__outmode)) + else: + print "No Results found" # }}} def editEntry(__passdict): # {{{ - __count = len(__passdict['__ID']) - for i in range(0, __count): - print '---------------------------' - print 'Changing Entry with ID: ' + str(__passdict['__ID'][i]) + '\nENTER for no changes.' - for __column in __passdict: - __input = '' - if __column != '__ID': - if __passdict[__column][i] is None: - __passdict[__column][i] = '' - __input = raw_input(__column + ' (' + str(__passdict[__column][i]) + '): ') - if search('^"""',__input): - tempinput = sub('^"""','',__input) + '\n' - __input = raw_input(' '.ljust(len(__column),'>') + ':') - while not search('"""$',__input): - tempinput = tempinput + __input + '\n' - __input = raw_input(' '.ljust(len(__column),'>') + ':') - tempinput = tempinput + sub('"""$','',__input) - __passdict[__column][i] = tempinput - elif __input != '': - __passdict[__column][i] = __input - return __passdict + __count = len(__passdict['__ID']) + for i in range(0, __count): + print '---------------------------' + print 'Changing Entry with ID: ' + str(__passdict['__ID'][i]) + '\nENTER for no changes.' + for __column in __passdict: + __input = '' + if __column != '__ID': + if __passdict[__column][i] is None: + __passdict[__column][i] = '' + __input = raw_input(__column + ' (' + str(__passdict[__column][i]) + '): ') + if search('^"""',__input): + tempinput = sub('^"""','',__input) + '\n' + __input = raw_input(' '.ljust(len(__column),'>') + ':') + while not search('"""$',__input): + tempinput = tempinput + __input + '\n' + __input = raw_input(' '.ljust(len(__column),'>') + ':') + tempinput = tempinput + sub('"""$','',__input) + __passdict[__column][i] = tempinput + elif __input != '': + __passdict[__column][i] = __input + return __passdict # }}} def deleteEntry(__passdict): # {{{ - __count = len(__passdict['__ID']) - __ids = [] - print '\n---------------------------' - for i in range(0, __count): - __input = None - while __input != 'y' and __input != 'n': - __input = raw_input('Delete Entry with ID ' + str(__passdict['__ID'][i]) + ' (y|n)?') - if __input == 'y': - __ids.append(__passdict['__ID'][i]) - return __ids + __count = len(__passdict['__ID']) + __ids = [] + print '\n---------------------------' + for i in range(0, __count): + __input = None + while __input != 'y' and __input != 'n': + __input = raw_input('Delete Entry with ID ' + str(__passdict['__ID'][i]) + ' (y|n)?') + if __input == 'y': + __ids.append(__passdict['__ID'][i]) + return __ids # }}} def createEntry(columns): # {{{ - Entry = {} - print "Adding a new Entry to our passfile" - for column in columns: - value = raw_input(column + ': ') - if search('^"""',value): - tempval = sub('^"""','',value) + '\n' - value = raw_input(column + ': ') - while not search('"""$',value): - tempval = tempval + value + '\n' - value = raw_input(column + ': ') - tempval = tempval + sub('"""$','',value) - value = tempval - Entry.update({ column : value }) - return Entry + Entry = {} + print "Adding a new Entry to our passfile" + for column in columns: + value = raw_input(column + ': ') + if search('^"""',value): + tempval = sub('^"""','',value) + '\n' + value = raw_input(column + ': ') + while not search('"""$',value): + tempval = tempval + value + '\n' + value = raw_input(column + ': ') + tempval = tempval + sub('"""$','',value) + value = tempval + Entry.update({ column : value }) + return Entry # }}} def parseArgs(versions): # {{{ - __optionsdict = {} + __optionsdict = {} - parser = OptionParser( "%prog [Options] [Keywords]", - description = "SPD - Simple Password Displayer - CLI", - version = """\nspdInterface """ + versions['spdInterface'] + - """\nspdConfig """ + versions['spdConfig'] + - """\nspdDefaults """ + versions['spdDefaults'] + - """\nConfigFile """ + versions['ConfigFile'] + - """\nCLI """ + __version__, - epilog = """With no parameters it will print out everything! - Please report Bugs or Feature Request at http://spd.sourceforge.net""") + parser = OptionParser( "%prog [Options] [Keywords]", + description = "SPD - Simple Password Displayer - CLI", + version = """\nspdInterface """ + versions['spdInterface'] + + """\nspdConfig """ + versions['spdConfig'] + + """\nspdDefaults """ + versions['spdDefaults'] + + """\nConfigFile """ + versions['ConfigFile'] + + """\nCLI """ + __version__, + epilog = """With no parameters it will print out everything! + Please report Bugs or Feature Request at http://spd.sourceforge.net""") - parser.add_option( "-a", "--add", - action="store_true", - dest = "addEntry", - default=False, - help = "Add an Entry") + parser.add_option( "-a", "--add", + action="store_true", + dest = "addEntry", + default=False, + help = "Add an Entry") - parser.add_option( "-e", "--edit", - action = "store_true", - dest ="editEntry", - help ="Edit given Entries (IDs)") + parser.add_option( "-e", "--edit", + action = "store_true", + dest ="editEntry", + help ="Edit given Entries (IDs)") - parser.add_option( "-d", "--delete", - action = "store_true", - dest ="deleteEntry", - default = False, - help ="Delete given Entries") - - group = OptionGroup(parser, "Input Manipulation") + parser.add_option( "-d", "--delete", + action = "store_true", + dest ="deleteEntry", + default = False, + help ="Delete given Entries") + + group = OptionGroup(parser, "Input Manipulation") - group.add_option( "--id", - action="store_true", - dest ="byid", - default=False, - help ="Handle Input given as ID(s)") + group.add_option( "--id", + action="store_true", + dest ="byid", + default=False, + help ="Handle Input given as ID(s)") - parser.add_option_group(group) + parser.add_option_group(group) - group = OptionGroup(parser, "Output Manipulation") + group = OptionGroup(parser, "Output Manipulation") - group.add_option( "-w", "--wide", - action="store_true", - dest = "widemode", - default=False, - help = "print output in wide mode (means as a table)") + group.add_option( "-w", "--wide", + action="store_true", + dest = "widemode", + default=False, + help = "print output in wide mode (means as a table)") - group.add_option( "-p", "--password-only", - action="store_true", - dest = "pwonly", - default=False, - help = "print Password only of first match, usefull for piping (e.g. in rdesktop)") + group.add_option( "-p", "--password-only", + action="store_true", + dest = "pwonly", + default=False, + help = "print Password only of first match, usefull for piping (e.g. in rdesktop)") - parser.add_option_group(group) - - - #parser.add_option( "-l", "--local", - # action="store_true", - # dest = "localStore", - # default=False, - # help = "do not operate on the configured RCS, only use the local password container") - # - #parser.add_option( "--passfile", - # dest = "passfile", - # help = "do not use the confgured passfile but the one given here") + parser.add_option_group(group) + + + #parser.add_option( "-l", "--local", + # action="store_true", + # dest = "localStore", + # default=False, + # help = "do not operate on the configured RCS, only use the local password container") + # + #parser.add_option( "--passfile", + # dest = "passfile", + # help = "do not use the confgured passfile but the one given here") - group = OptionGroup(parser, "Columns Manipulation") + group = OptionGroup(parser, "Columns Manipulation") - group.add_option( "--add-columns", - action="store_true", - dest = "addColumn", - default=False, - help = "Add given Column(s)") + group.add_option( "--add-columns", + action="store_true", + dest = "addColumn", + default=False, + help = "Add given Column(s)") - group.add_option( "--delete-columns", - action = "store_true", - dest ="deleteColumn", - default = False, - help ="Delete Columns given") + group.add_option( "--delete-columns", + action = "store_true", + dest ="deleteColumn", + default = False, + help ="Delete Columns given") - parser.add_option_group(group) + parser.add_option_group(group) - (options, args) = parser.parse_args() + (options, args) = parser.parse_args() - if options.widemode: - __outmode = 'wide' - else: - __outmode = 'line' + if options.widemode: + __outmode = 'wide' + else: + __outmode = 'line' - __optionsdict.update({ 'args' : args, - 'byid' : options.byid, - 'outmode' : __outmode, - 'pwonly' : options.pwonly }) + __optionsdict.update({ 'args' : args, + 'byid' : options.byid, + 'outmode' : __outmode, + 'pwonly' : options.pwonly }) - if options.addEntry: - return ["addEntry", __optionsdict] - elif options.deleteEntry: - return ["deleteEntry", __optionsdict] - elif options.editEntry: - return ["editEntry", __optionsdict] + if options.addEntry: + return ["addEntry", __optionsdict] + elif options.deleteEntry: + return ["deleteEntry", __optionsdict] + elif options.editEntry: + return ["editEntry", __optionsdict] - elif options.deleteColumn: - return ["deleteColumn", __optionsdict] - elif options.addColumn: - return ["addColumn", __optionsdict] + elif options.deleteColumn: + return ["deleteColumn", __optionsdict] + elif options.addColumn: + return ["addColumn", __optionsdict] - return ["printPasswords", __optionsdict] + return ["printPasswords", __optionsdict] # }}} # EOF -# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3 +# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4 Modified: branches/spd-ng/src/spdStore/__init__.py =================================================================== --- branches/spd-ng/src/spdStore/__init__.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdStore/__init__.py 2012-09-24 21:12:21 UTC (rev 343) @@ -1,9 +1,6 @@ '''spdStore Module -This Modules takes Care of the storage Engine used by SPD. -Currently Implemented Storage Types are -- plain -- gpg''' +This Modules takes Care of the storage Engine used by SPD.''' -# EOF -# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3 +#EOF +# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4 Modified: branches/spd-ng/src/spdStore/devel.py =================================================================== --- branches/spd-ng/src/spdStore/devel.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdStore/devel.py 2012-09-24 21:12:21 UTC (rev 343) @@ -1,26 +1,17 @@ # -*- coding: utf-8 -*- -# +'''spdStore.devel +This module is just for development. No real data should be written into that database''' + import sqlite3 -testdb = '/home/scabrera/Projects/spd/branches/spd-ng/test.db' +testdb = '/home/scabrera/Projects/spd/branches/spd-ng/src/test.db' -def __sql2dict(self,cursor,row): # {{{ - result = {} - for ColumnNr, Column in enumerate(cursor.description): - result[Column[0]] = row[ColumnNr] - - return result - -# }}} - def getData(): # {{{ db = sqlite3.connect(testdb) - db.row_factory = __sql2dict - dbc = db.cursor() - - query = 'SELECT * FROM Main' - dbc.execute(query) - print str(dbc) + return db +# }}} - +def saveData(): # {{{ + pass +# }}} Modified: branches/spd-ng/src/spdStore/plain.py =================================================================== --- branches/spd-ng/src/spdStore/plain.py 2012-09-23 21:13:56 UTC (rev 342) +++ branches/spd-ng/src/spdStore/plain.py 2012-09-24 21:12:21 UTC (rev 343) @@ -2,3 +2,4 @@ # pass +# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4 Modified: branches/spd-ng/src/test.db =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |