You can subscribe to this list here.
| 2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(4) |
Jul
(10) |
Aug
(2) |
Sep
(2) |
Oct
(2) |
Nov
|
Dec
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2009 |
Jan
|
Feb
|
Mar
(3) |
Apr
(4) |
May
|
Jun
|
Jul
|
Aug
(2) |
Sep
(23) |
Oct
(3) |
Nov
(2) |
Dec
|
| 2010 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
(3) |
Jun
(6) |
Jul
|
Aug
|
Sep
(20) |
Oct
|
Nov
(3) |
Dec
(9) |
| 2011 |
Jan
(3) |
Feb
(1) |
Mar
|
Apr
(2) |
May
|
Jun
(3) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2012 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
(1) |
Sep
(5) |
Oct
(2) |
Nov
(1) |
Dec
|
|
From: <Z3...@us...> - 2012-11-02 20:56:42
|
Revision: 348
http://spd.svn.sourceforge.net/spd/?rev=348&view=rev
Author: Z3po
Date: 2012-11-02 20:56:35 +0000 (Fri, 02 Nov 2012)
Log Message:
-----------
restructured ConfigObject
Modified Paths:
--------------
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/spdInterfaces/__init__.py
branches/spd-ng/src/spdInterfaces/cli.py
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2012-10-14 17:40:17 UTC (rev 347)
+++ branches/spd-ng/src/spdConfig.py 2012-11-02 20:56:35 UTC (rev 348)
@@ -6,7 +6,7 @@
from ConfigParser import RawConfigParser
-from sys import exit
+import spdDefaults
import os
class Config(object): # {{{
@@ -22,32 +22,32 @@
def __init__(self, configfile='~/.spd/config'): # {{{
self.__configfile = os.path.expanduser(configfile)
+ if not self.__checkConfigFileExist:
+ spdDefaults.createDefaultConfig(self.ConfigObject)
# }}}
def __checkConfigFileExist(self): # {{{
"""Does the Config file exist?"""
if os.access(self.__configfile, os.F_OK):
- return 0
+ return True
else:
- return 1
+ return False
# }}}
def __checkConfigFileReadable(self): # {{{
"""Is the Config file readable?"""
- reval = self.__checkConfigFileExist()
- config = RawConfigParser()
+ if self.__checkConfigFileExist():
+ config = RawConfigParser()
- if reval > 0:
- return reval, config
-
- if os.access(self.__configfile,os.R_OK):
- config.read(self.__configfile)
- return 0,config
+ if os.access(self.__configfile,os.R_OK):
+ config.read(self.__configfile)
+ return config
+ else:
+ raise OSError('ConfigFile unreadable')
else:
- print 'ConfigFile not readable!'
- exit(2)
+ return False
# }}}
def __checkConfigFileWriteable(self): # {{{
@@ -56,10 +56,9 @@
if os.access(self.__configfile,os.W_OK):
configfile = open(self.__configfile, 'wb')
else:
- print 'ConfigFile not writeable!'
- exit(2)
+ raise OSError('ConfigFile not writeable!')
- return 0, configfile
+ return configfile
# }}}
def __writeConfigFile(self,config): # {{{
@@ -74,46 +73,51 @@
"""Check if a given section exists.
# section: the given section."""
- reval, config = self.__checkConfigFileReadable()
- if reval > 0:
- return reval, config
+ config = self.__checkConfigFileReadable()
+
+ if not config:
+ raise OSError('ConfigFile does not exist!')
if config.has_section(section):
- return 0, config
-
- return 2, config
+ return config
+ else:
+ return False
# }}}
def __addSection(self, section): # {{{
"""create a section if its not in configfile.
# section: the section to create."""
- reval, config = self.__hasSection(section)
+ config = self.__hasSection(section)
- if reval == 2:
+ if not config:
config.add_section(section)
self.__writeConfigFile(config)
-
+ return True
else:
- return reval
-
- return 0
+ return False
# }}}
def __delSection(self, section): # {{{
"""delete a Section from configfile.
# section: the section to delete."""
- reval, config = self.__hasSection(section)
+ config = self.__hasSection(section)
- if reval == 0:
+ if config:
config.remove_section(section)
self.__writeConfigFile(config)
+ else:
+ return False
+ # }}}
- if reval > 0:
- return reval
-
- return 0
+ def setPreset(self, preset): # {{{
+ """Sets the used Preset"""
+ if preset not in self.getSections():
+ if preset != 'Main':
+ raise KeyError('Preset unavailable!')
+ else:
+ self.ConfigSection = preset
# }}}
def getOption(self, section, option): # {{{
@@ -121,15 +125,15 @@
# section: in which section is the option configured?
# option: option to return."""
- reval, config = self.__hasSection(section)
+ config = self.__hasSection(section)
- if reval > 0:
- return reval, None
+ if not config:
+ return False
if config.has_option(section,option):
- return 0, config.get(section,option)
+ return config.get(section,option)
else:
- return 4, None
+ return False
# }}}
def setOption(self, section, option, value): # {{{
@@ -138,18 +142,14 @@
# option: option to set/change.
# value: set the option to this value."""
- reval, config = self.__hasSection(section)
+ config = self.__hasSection(section)
- if reval > 0:
- return reval
-
- config.set(section, option, value)
- reval = self.__writeConfigFile(config)
-
- if reval > 0:
- return reval
-
- return 0
+ if not config:
+ config.set(section, option, value)
+ self.__writeConfigFile(config)
+ return True
+ else:
+ return False
# }}}
def delOption(self, section, option): # {{{
@@ -157,181 +157,97 @@
# section: which section holds the option?
# option: option to delete."""
- reval, config = self.__hasSection(section)
-
- if reval > 0:
- return reval
-
- reval, option = self.getOption(section,option)
-
- if reval > 0:
- return reval
-
- config.remove_option(section,option)
- reval = self.__writeConfigFile(config)
-
- if reval > 0:
- return reval
-
- return 0
+ if self.__hasSection(section):
+ config = self.getOption(section,option)
+ if config:
+ config.remove_option(section,option)
+ self.__writeConfigFile(config)
+ return True
# }}}
def getAllSections(self): # {{{
- reval, config = self.__checkConfigFileReadable()
- if reval > 0:
- return reval, config
+ config = self.__checkConfigFileReadable()
+ if not config:
+ raise OSError('ConfigFile does not exist!')
+
if config.sections():
return 0, config.sections()
return 2, config
# }}}
- def getSections(self, raw=False): # {{{
+ def getSections(self): # {{{
"""Return all sections from configfile."""
- reval, config = self.__checkConfigFileReadable()
+ config = self.__checkConfigFileReadable()
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
+ if not config:
+ raise OSError('ConfigFile does not exist!')
- if raw:
- return 0, config.sections()
-
return config.sections()
-
# }}}
def addConfigSection(self, section): # {{{
- reval = self.__addSection(section)
+ set = self.__addSection(section)
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
+ if not set:
+ raise KeyError('Section already exists!')
# }}}
- def getConfigVersion(self, raw=False): # {{{
+ def getConfigVersion(self): # {{{
"""Return the config version."""
- reval, option = self.getOption(self.ConfigSection,"version")
-
- if reval > 1 and reval < 2:
- raise KeyError(self.ReturnCodes[reval]) # don't tolerate These
-
- if reval > 0:
- if raw:
- return reval, None
-
- raise KeyError(self.ReturnCodes[reval])
-
- if raw:
- return reval, option
-
- return option
+ return self.getOption(self.ConfigSection,"version")
# }}}
def setConfigVersion(self, version): # {{{
"""set the config version to the given version.
# version: version number."""
- reval = self.setOption(self.ConfigSection,"version",version)
-
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
+ return self.setOption(self.ConfigSection,"version",version)
# }}}
- def getClientmode(self, raw=False): # {{{
- '''get the clientmode.
- # return the clientmode option'''
+ def getClientmode(self): # {{{
+ '''get the clientmode.
+ # return the clientmode option'''
- reval, clientmode = self.getOption(self.ConfigSection, 'clientmode')
-
- if reval > 0 and reval < 4:
- raise KeyError(self.ReturnCodes[reval])
-
- if reval > 0:
- if raw:
- return reval, None
- else:
- raise KeyError(self.ReturnCodes[reval])
-
- if raw:
- return reval, clientmode
-
- return clientmode
+ return self.getOption(self.ConfigSection, 'clientmode')
# }}}
def setClientmode(self, clientmode): # {{{
"""set the clientmode.
# clientmode: clientmode to use."""
- reval = self.setOption(self.ConfigSection,"clientmode",clientmode)
-
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
+ return self.setOption(self.ConfigSection,"clientmode",clientmode)
# }}}
- def getPasswordfield(self, section=ConfigSection, raw=False): # {{{
- '''get the clientmode.
- # return the Password Column'''
+ def getPasswordfield(self, section=ConfigSection): # {{{
+ '''get the clientmode.
+ # return the Password Column'''
- reval, clientmode = self.getOption(section, 'passwordfield')
-
- if reval > 0 and reval < 4:
- raise KeyError(self.ReturnCodes[reval])
-
- if reval > 0:
- return reval, None
-
- if raw:
- return reval, clientmode
-
- return clientmode
+ return self.getOption(section, 'passwordfield')
# }}}
def setPasswordfield(self, passcolumn, section=ConfigSection): # {{{
"""set the Password Column.
# passcolumn: passcolumn to set."""
- reval = self.setOption(section,"passwordfield",passcolumn)
-
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
+ return self.setOption(section,"passwordfield",passcolumn)
# }}}
- def getStoretype(self, raw=False, section=ConfigSection): # {{{
- '''get the clientmode.
- # return the clientmode option'''
+ def getStoretype(self, section=ConfigSection): # {{{
+ '''get the clientmode.
+ # return the clientmode option'''
- reval, storetype = self.getOption(section, 'storetype')
-
- if reval > 0 and reval < 4:
- raise KeyError(self.ReturnCodes[reval])
-
- if reval > 0:
- if raw:
- return reval, None
- else:
- raise KeyError(self.ReturnCodes[reval])
-
- if raw:
- return reval, storetype
-
- return storetype
+ return self.getOption(section, 'storetype')
# }}}
def getPasswordfile(self, section=ConfigSection): # {{{
- '''get the password field.
- # return the password field'''
+ '''get the password field.
+ # return the password field'''
- reval, storetype = self.getOption(section, 'file')
-
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
-
- if reval > 0:
- raise KeyError(self.ReturnCodes[reval])
-
- return storetype
+ return self.getOption(section, 'file')
# }}}
# }}}
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2012-10-14 17:40:17 UTC (rev 347)
+++ branches/spd-ng/src/spdInterface.py 2012-11-02 20:56:35 UTC (rev 348)
@@ -22,7 +22,6 @@
import os
import string
import spdConfig
-import spdDefaults
import spdCore
@@ -35,48 +34,34 @@
def __init__(self,clientmode=False): # {{{
"""init procedure"""
- initcheck = {}
- self.ConfigObject = spdConfig.Config()
-
- self.core = spdCore.Core(self.ConfigObject)
-
if not os.access(self.spddir, os.F_OK):
os.mkdir(self.spddir)
- reval, self.configversion = self.ConfigObject.getConfigVersion(raw=True)
+ self.ConfigObject = spdConfig.Config()
- if reval == 1:
- spdDefaults.createDefaultConfig(self.ConfigObject)
- self.configversion = self.ConfigObject.getConfigVersion()
- elif reval == 4:
+ self.configversion = self.ConfigObject.getConfigVersion()
+
+ if not self.configversion:
print 'ConfigVersion not found...setting Default one\n'
- __blackhole = raw_input('Press any key')
self.ConfigObject.setConfigVersion('0.3-alpha')
self.configversion = self.ConfigObject.getConfigVersion()
+ __blackhole = raw_input('Press any key')
if not clientmode:
- reval, initcheck['clientmode'] = self.ConfigObject.getClientmode(raw=True)
- if reval == 4:
+ clientmode = self.ConfigObject.getClientmode()
+ if not clientmode:
print 'Default Clientmode not found...setting it to CLI\n'
- __blackhole = raw_input('Press any key')
self.ConfigObject.setClientmode('cli')
- initcheck.update({ 'clientmode' : self.ConfigObject.getClientmode() })
+ clientmode = self.ConfigObject.getClientmode()
+ __blackhole = raw_input('Press any key')
- reval, __passwordfield = self.ConfigObject.getPasswordfield(raw=True)
-
- if reval == 0:
- initcheck.update({ 'passwordfield' : __passwordfield })
-
- if not clientmode:
- clientmode = initcheck['clientmode']
-
self.client = __import__('spdInterfaces.' + clientmode.lower(), fromlist=['',])
- if 'passwordfield' in initcheck:
- self.client.passwordfield = initcheck['passwordfield']
+ passwordfield = self.ConfigObject.getPasswordfield()
- del initcheck
+ if passwordfield:
+ self.client.passwordfield
# }}}
def __findPasswords(self,args): # {{{
@@ -102,6 +87,14 @@
return passdict
# }}}
+ def updatePreset(self, preset): # {{{
+ self.ConfigObject.setPreset(preset)
+ # }}}
+
+ def loadStore(self): # {{{
+ self.core = spdCore.Core(self.ConfigObject)
+ # }}}
+
def saveData(self, __blackhole='nothing'): # {{{
self.core.saveData()
# }}}
@@ -179,7 +172,10 @@
# }}}
def main(self): # {{{
- functions, args = self.client.parseArgs(self.core.version)
+ functions, args = self.client.parseArgs()
+ if 'preset' in args:
+ self.updatePreset(args['preset'])
+ self.loadStore()
if type(functions).__name__ == 'tuple':
for function in functions:
getattr(self, function)(args)
Modified: branches/spd-ng/src/spdInterfaces/__init__.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/__init__.py 2012-10-14 17:40:17 UTC (rev 347)
+++ branches/spd-ng/src/spdInterfaces/__init__.py 2012-11-02 20:56:35 UTC (rev 348)
@@ -7,3 +7,5 @@
'''spdInterfaces Module
This Module takes Care of the Interface used by SPD.'''
+
+# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4
Modified: branches/spd-ng/src/spdInterfaces/cli.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/cli.py 2012-10-14 17:40:17 UTC (rev 347)
+++ branches/spd-ng/src/spdInterfaces/cli.py 2012-11-02 20:56:35 UTC (rev 348)
@@ -15,6 +15,7 @@
from re import sub, search
passwordfield = 'Password'
+version = '0.3'
def __ErrorHandler(function,message): # {{{
"""ErrorHandler of the Client Module.
@@ -167,12 +168,12 @@
return Entry
# }}}
-def parseArgs(coreversion): # {{{
+def parseArgs(): # {{{
__optionsdict = {}
parser = OptionParser( "%prog [Options] [Keywords]",
description = "SPD - Simple Password Displayer - CLI",
- version = coreversion,
+ version = version,
epilog = """With no parameters it will print out everything!
Please report Bugs or Feature Request at http://spd.sourceforge.net""")
@@ -226,11 +227,13 @@
# 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( "--preset",
+ dest = "preset",
+ default='Main',
+ help = "Use the given preset instead of Main")
+
group = OptionGroup(parser, "Columns Manipulation")
group.add_option( "--add-columns",
@@ -263,7 +266,8 @@
__optionsdict.update({ 'args' : args,
'byid' : options.byid,
'outmode' : __outmode,
- 'pwonly' : options.pwonly })
+ 'pwonly' : options.pwonly,
+ 'preset' : options.preset})
if options.addEntry:
return [("fetchData","addEntry","saveData"), __optionsdict]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-10-14 17:40:24
|
Revision: 347
http://spd.svn.sourceforge.net/spd/?rev=347&view=rev
Author: Z3po
Date: 2012-10-14 17:40:17 +0000 (Sun, 14 Oct 2012)
Log Message:
-----------
added gpg support. Mostly copied functionality from current trunk to spd-ng...need to look into that. spdConfig Module needs to be redone....don't know why i thought it might be cool that way o.0
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/cli.py
branches/spd-ng/src/spdStore/devel.py
branches/spd-ng/src/spdStore/plain.py
Added Paths:
-----------
branches/spd-ng/src/spdStore/gpg.py
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2012-10-07 14:08:40 UTC (rev 346)
+++ branches/spd-ng/src/spdConfig.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -17,6 +17,7 @@
ReturnCodes = { 1 : 'Missing ConfigFile',
2 : 'Section not found',
4 : 'Option not found' }
+
ConfigSection = 'Main'
def __init__(self, configfile='~/.spd/config'): # {{{
@@ -69,7 +70,7 @@
config.write(configfile)
# }}}
- def __hasSection(self,section): # {{{
+ def __hasSection(self, section): # {{{
"""Check if a given section exists.
# section: the given section."""
@@ -83,7 +84,7 @@
return 2, config
# }}}
- def __addSection(self,section): # {{{
+ def __addSection(self, section): # {{{
"""create a section if its not in configfile.
# section: the section to create."""
@@ -99,7 +100,7 @@
return 0
# }}}
- def __delSection(self,section): # {{{
+ def __delSection(self, section): # {{{
"""delete a Section from configfile.
# section: the section to delete."""
@@ -115,7 +116,7 @@
return 0
# }}}
- def __getOption(self,section,option): # {{{
+ def getOption(self, section, option): # {{{
"""Return the option from section.
# section: in which section is the option configured?
# option: option to return."""
@@ -131,7 +132,7 @@
return 4, None
# }}}
- def __setOption(self,section,option,value): # {{{
+ def setOption(self, section, option, value): # {{{
"""Create or set the given option.
# section: section of the option.
# option: option to set/change.
@@ -142,7 +143,7 @@
if reval > 0:
return reval
- config.set(section,option,value)
+ config.set(section, option, value)
reval = self.__writeConfigFile(config)
if reval > 0:
@@ -151,7 +152,7 @@
return 0
# }}}
- def __delOption(self,section,option): # {{{
+ def delOption(self, section, option): # {{{
"""delete an option.
# section: which section holds the option?
# option: option to delete."""
@@ -161,7 +162,7 @@
if reval > 0:
return reval
- reval, option = self.__getOption(section,option)
+ reval, option = self.getOption(section,option)
if reval > 0:
return reval
@@ -201,7 +202,7 @@
# }}}
- def addConfigSection(self,section): # {{{
+ def addConfigSection(self, section): # {{{
reval = self.__addSection(section)
if reval > 0:
@@ -211,7 +212,7 @@
def getConfigVersion(self, raw=False): # {{{
"""Return the config version."""
- reval, option = self.__getOption("Main","version")
+ reval, option = self.getOption(self.ConfigSection,"version")
if reval > 1 and reval < 2:
raise KeyError(self.ReturnCodes[reval]) # don't tolerate These
@@ -228,11 +229,11 @@
return option
# }}}
- def setConfigVersion(self,version): # {{{
+ def setConfigVersion(self, version): # {{{
"""set the config version to the given version.
# version: version number."""
- reval = self.__setOption("Main","version",version)
+ reval = self.setOption(self.ConfigSection,"version",version)
if reval > 0:
raise KeyError(self.ReturnCodes[reval])
@@ -242,7 +243,7 @@
'''get the clientmode.
# return the clientmode option'''
- reval, clientmode = self.__getOption('Main', 'clientmode')
+ reval, clientmode = self.getOption(self.ConfigSection, 'clientmode')
if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
@@ -259,30 +260,27 @@
return clientmode
# }}}
- def setClientmode(self,clientmode): # {{{
+ def setClientmode(self, clientmode): # {{{
"""set the clientmode.
# clientmode: clientmode to use."""
- reval = self.__setOption("Main","clientmode",clientmode)
+ reval = self.setOption(self.ConfigSection,"clientmode",clientmode)
if reval > 0:
raise KeyError(self.ReturnCodes[reval])
# }}}
- def getPasswordfield(self, raw=False): # {{{
+ def getPasswordfield(self, section=ConfigSection, raw=False): # {{{
'''get the clientmode.
# return the Password Column'''
- reval, clientmode = self.__getOption('Main', 'passwordfield')
+ reval, clientmode = self.getOption(section, 'passwordfield')
if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
if reval > 0:
- if raw:
return reval, None
- else:
- raise KeyError(self.ReturnCodes[reval])
if raw:
return reval, clientmode
@@ -290,21 +288,21 @@
return clientmode
# }}}
- def setPasswordfield(self,passcolumn): # {{{
+ def setPasswordfield(self, passcolumn, section=ConfigSection): # {{{
"""set the Password Column.
# passcolumn: passcolumn to set."""
- reval = self.__setOption("Main","passwordfield",passcolumn)
+ reval = self.setOption(section,"passwordfield",passcolumn)
if reval > 0:
raise KeyError(self.ReturnCodes[reval])
# }}}
- def getStoretype(self, raw=False): # {{{
+ def getStoretype(self, raw=False, section=ConfigSection): # {{{
'''get the clientmode.
# return the clientmode option'''
- reval, storetype = self.__getOption('Main', 'storetype')
+ reval, storetype = self.getOption(section, 'storetype')
if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
@@ -321,24 +319,18 @@
return storetype
# }}}
- def getPasswordfile(self, raw=False): # {{{
+ def getPasswordfile(self, section=ConfigSection): # {{{
'''get the password field.
# return the password field'''
- reval, storetype = self.__getOption('Main', 'file')
+ reval, storetype = self.getOption(section, 'file')
- if reval > 0 and reval < 4:
+ if reval > 0:
raise KeyError(self.ReturnCodes[reval])
if reval > 0:
- if raw:
- return reval, None
- else:
raise KeyError(self.ReturnCodes[reval])
- if raw:
- return reval, storetype
-
return storetype
# }}}
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2012-10-07 14:08:40 UTC (rev 346)
+++ branches/spd-ng/src/spdCore.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -22,11 +22,15 @@
# create the database from the stuff out of the store
def __init__(self,ConfigObject): # {{{
+ self.ConfigObject = ConfigObject
self.PasswordPreset = ConfigObject.ConfigSection
self.PasswordColumn = ConfigObject.getPasswordfield()
self.PasswordFile = ConfigObject.getPasswordfile()
self.spdStore = __import__('spdStore.' + ConfigObject.getStoretype(), fromlist=['',])
- self.db = self.spdStore.getData(self.PasswordFile, self.PasswordPreset)
+ # }}}
+
+ def fetchData(self): # {{{
+ self.db = self.spdStore.getData(self.ConfigObject)
self.db.row_factory = self.__sql2dict
self.dbc = self.db.cursor()
# }}}
@@ -41,7 +45,7 @@
def saveData(self): # {{{
if self.spdStore != None:
- self.spdStore.saveData(self.PasswordFile, self.PasswordPreset, self.db)
+ self.spdStore.saveData(self.ConfigObject, self.db)
# }}}
def searchEntry(self,SearchList,byid=False): # {{{
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2012-10-07 14:08:40 UTC (rev 346)
+++ branches/spd-ng/src/spdInterface.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -106,6 +106,10 @@
self.core.saveData()
# }}}
+ def fetchData(self, __blackhole='nothing'): # {{{
+ self.core.fetchData()
+ # }}}
+
def printPasswords(self,args): # {{{
passdict = self.__findPasswords(args)
self.client.printPasswords(passdict, args)
Modified: branches/spd-ng/src/spdInterfaces/cli.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/cli.py 2012-10-07 14:08:40 UTC (rev 346)
+++ branches/spd-ng/src/spdInterfaces/cli.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -266,20 +266,20 @@
'pwonly' : options.pwonly })
if options.addEntry:
- return [("addEntry","saveData"), __optionsdict]
+ return [("fetchData","addEntry","saveData"), __optionsdict]
elif options.deleteEntry:
- return [("deleteEntry","saveData"), __optionsdict]
+ return [("fetchData","deleteEntry","saveData"), __optionsdict]
elif options.editEntry:
- return [("editEntry","saveData"), __optionsdict]
+ return [("fetchData","editEntry","saveData"), __optionsdict]
elif options.deleteColumn:
- return [("deleteColumn","saveData"), __optionsdict]
+ return [("fetchData","deleteColumn","saveData"), __optionsdict]
elif options.renameColumn:
- return [("renameColumn","saveData"), __optionsdict]
+ return [("fetchData","renameColumn","saveData"), __optionsdict]
elif options.addColumn:
- return [("addColumn","saveData"), __optionsdict]
+ return [("fetchData","addColumn","saveData"), __optionsdict]
- return ["printPasswords", __optionsdict]
+ return [("fetchData","printPasswords"), __optionsdict]
# }}}
# EOF
Modified: branches/spd-ng/src/spdStore/devel.py
===================================================================
--- branches/spd-ng/src/spdStore/devel.py 2012-10-07 14:08:40 UTC (rev 346)
+++ branches/spd-ng/src/spdStore/devel.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -9,14 +9,14 @@
This module is just for development. No real data should be written into that database'''
import sqlite3
+from os import path as ospath
-testdb = '/home/scabrera/Projects/spd/branches/spd-ng/src/test.db'
-
-def getData(passwordfile, passwordpreset): # {{{
- db = sqlite3.connect(testdb)
+def getData(ConfigObject): # {{{
+ passwordfile = ConfigObject.getPasswordfile()
+ db = sqlite3.connect(ospath.expanduser(passwordfile))
return db
# }}}
-def saveData(passwordfile, passwordpreset, database): # {{{
+def saveData(ConfigObject, database): # {{{
pass
# }}}
Copied: branches/spd-ng/src/spdStore/gpg.py (from rev 345, branches/spd-ng/src/spdStore/plain.py)
===================================================================
--- branches/spd-ng/src/spdStore/gpg.py (rev 0)
+++ branches/spd-ng/src/spdStore/gpg.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -0,0 +1,136 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+'''This storage module handles plaintext files seperated by "seperator"'''
+
+import sqlite3
+from os import path as ospath
+from pyme import core, callbacks
+from re import sub as resub
+
+separator = '\t'
+
+def getSQLData(passwordpreset, sqlitedb): # {{{
+ sqlitecursor = sqlitedb.cursor()
+
+ query = "pragma Table_info('" + passwordpreset + "')"
+ sqlitecursor.execute(query)
+
+ columns = []
+ for i in sqlitecursor:
+ if i['name'] == "__ID":
+ continue
+ columns.append(str(i['name']))
+
+ query = "SELECT * FROM " + passwordpreset
+ sqlitecursor.execute(query)
+ data = sqlitecursor.fetchall()
+
+ return columns, data
+ # }}}
+
+def getData(ConfigObject): #{{{
+ """This function reads the password file"""
+
+ passwordfile = ConfigObject.getPasswordfile()
+ passwordpreset = ConfigObject.ConfigSection
+
+ enc = core.Data(file=ospath.expanduser(passwordfile))
+ dec = core.Data()
+ c = core.Context()
+
+ c.set_passphrase_cb(callbacks.passphrase_stdin, 'for decryption.')
+ c.op_decrypt(enc,dec)
+ dec.seek(0,0)
+
+ # make fobj "something" like a file
+ passfile = dec.read().split('\n')
+ del passfile[len(passfile)-1]
+
+ sqlitedb = sqlite3.connect(":memory:")
+ sqlitecursor = sqlitedb.cursor()
+ query = "CREATE TABLE " + passwordpreset + " ( __ID INTEGER PRIMARY KEY,"
+
+ for linecount, i in enumerate(passfile):
+ i = resub('\'','\'\'\'',i)
+ line = i.strip('\n').split(separator)
+
+ if linecount == 0: # the first line defines the collumns
+ for column in line:
+ query += '`' + column + "` TEXT, "
+ query = query[0:-2] + ' )'
+ sqlitecursor.execute(query)
+
+ query = "INSERT INTO " + passwordpreset + " ( "
+ for column in line:
+ query += column + ', '
+ query = query[0:-2] + ' ) VALUES ( \''
+ continue
+
+ inserts = ""
+ for column in line:
+ inserts += column + '\', \''
+ inserts = inserts[0:-4] + '\' )'
+ sqlitecursor.execute(query + inserts)
+
+ sqlitedb.commit()
+ del passfile
+
+ return sqlitedb
+#}}}
+
+def saveData(ConfigObject, sqlitedb): # {{{
+
+ gpgrecipients = []
+ reval = 0
+ counter = 1
+ passwordpreset = ConfigObject.ConfigSection
+ passwordfile = ConfigObject.getPasswordfile()
+
+ reval, gpgrecipient = ConfigObject.getOption(passwordpreset, 'gpguser' + str(counter))
+
+ while gpgrecipient != None:
+ print str(counter)
+ print str(gpgrecipient)
+ counter += 1
+ gpgrecipients.append(gpgrecipient)
+ reval, gpgrecipient = ConfigObject.getOption(passwordpreset, 'gpguser' + str(counter))
+
+ columns, newdata = getSQLData(passwordpreset, sqlitedb)
+
+ insertdata = ""
+
+ for column in columns:
+ insertdata += column.encode("utf-8") + '\t'
+ insertdata = insertdata[0:-1] + '\n'
+
+ for datarow in newdata:
+ for column in columns:
+ insertdata += datarow[column].encode("utf-8") + '\t'
+ insertdata = insertdata[0:-1] + '\n'
+
+ plaindata = core.Data(insertdata)
+ cipher = core.Data()
+ c = core.Context()
+ c.set_armor(1)
+
+ # Get the first keys, it finds
+ RecipientKeys = []
+ for i in gpgrecipients:
+ c.op_keylist_start(i,0)
+ RecipientKeys.append(c.op_keylist_next())
+
+ # encrypt with RecipientKeys
+
+ c.op_encrypt(RecipientKeys, 1, plaindata, cipher)
+ cipher.seek(0,0)
+
+ gpgfile = open(ospath.expanduser(passwordfile),"w")
+ gpgfile.write(cipher.read())
+ gpgfile.close()
+
+# }}}
+
+# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4
Modified: branches/spd-ng/src/spdStore/plain.py
===================================================================
--- branches/spd-ng/src/spdStore/plain.py 2012-10-07 14:08:40 UTC (rev 346)
+++ branches/spd-ng/src/spdStore/plain.py 2012-10-14 17:40:17 UTC (rev 347)
@@ -6,6 +6,7 @@
'''This storage module handles plaintext files seperated by "seperator"'''
import sqlite3
+from os import path as ospath
separator = '\t'
@@ -28,11 +29,13 @@
return columns, data
# }}}
-
-def getData(passwordfile, passwordpreset): #{{{
+def getData(ConfigObject): #{{{
"""This function reads the password file"""
- passfile = open(passwordfile,"r")
+ passwordfile = ConfigObject.getPasswordfile()
+ passwordpreset = ConfigObject.ConfigSection
+
+ passfile = open(ospath.expanduser(passwordfile),"r")
sqlitedb = sqlite3.connect(":memory:")
sqlitecursor = sqlitedb.cursor()
query = "CREATE TABLE " + passwordpreset + " ( __ID INTEGER PRIMARY KEY,"
@@ -64,7 +67,11 @@
return sqlitedb
#}}}
-def saveData(passwordfile, passwordpreset, sqlitedb): # {{{
+def saveData(ConfigObject, sqlitedb): # {{{
+
+ passwordfile = ConfigObject.getPasswordfile()
+ passwordpreset = ConfigObject.ConfigSection
+
passfile = open(passwordfile,"w")
columns, newdata = getSQLData(passwordpreset, sqlitedb)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-10-07 14:08:48
|
Revision: 346
http://spd.svn.sourceforge.net/spd/?rev=346&view=rev
Author: Z3po
Date: 2012-10-07 14:08:40 +0000 (Sun, 07 Oct 2012)
Log Message:
-----------
restructured some of the code and did a little cleanup
Modified Paths:
--------------
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdDefaults.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/spdInterfaces/cli.py
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2012-09-27 20:53:33 UTC (rev 345)
+++ branches/spd-ng/src/spdConfig.py 2012-10-07 14:08:40 UTC (rev 346)
@@ -6,20 +6,17 @@
from ConfigParser import RawConfigParser
+from sys import exit
import os
-#import sys
class Config(object): # {{{
'''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' }
+ ReturnCodes = { 1 : 'Missing ConfigFile',
+ 2 : 'Section not found',
+ 4 : 'Option not found' }
ConfigSection = 'Main'
def __init__(self, configfile='~/.spd/config'): # {{{
@@ -32,7 +29,7 @@
if os.access(self.__configfile, os.F_OK):
return 0
else:
- return 2
+ return 1
# }}}
def __checkConfigFileReadable(self): # {{{
@@ -44,31 +41,22 @@
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
+ print 'ConfigFile not readable!'
+ exit(2)
# }}}
def __checkConfigFileWriteable(self): # {{{
"""Is the Config file writeable?"""
- reval = self.__checkConfigFileExist()
-
- 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
+ print 'ConfigFile not writeable!'
+ exit(2)
return 0, configfile
# }}}
@@ -77,14 +65,8 @@
'''Write the Config given.
# config: the configobject.'''
- reval, configfile = self.__checkConfigFileWriteable()
- if reval > 0:
- return reval
-
- try:
- config.write(configfile)
- except Exception, e:
- return 16
+ configfile = self.__checkConfigFileWriteable()
+ config.write(configfile)
# }}}
def __hasSection(self,section): # {{{
@@ -98,7 +80,7 @@
if config.has_section(section):
return 0, config
- return 32, config
+ return 2, config
# }}}
def __addSection(self,section): # {{{
@@ -107,13 +89,11 @@
reval, config = self.__hasSection(section)
- if reval > 0 and reval < 32 and reval is not 2:
- return reval
-
- config.add_section(section)
- reval = self.__writeConfigFile(config)
+ if reval == 2:
+ config.add_section(section)
+ self.__writeConfigFile(config)
- if reval > 0:
+ else:
return reval
return 0
@@ -125,12 +105,10 @@
reval, config = self.__hasSection(section)
- if reval > 0 and reval < 32:
- return reval
+ if reval == 0:
+ config.remove_section(section)
+ self.__writeConfigFile(config)
- config.remove_section(section)
- reval = self.__writeConfigFile(config)
-
if reval > 0:
return reval
@@ -150,7 +128,7 @@
if config.has_option(section,option):
return 0, config.get(section,option)
else:
- return 64, None
+ return 4, None
# }}}
def __setOption(self,section,option,value): # {{{
@@ -205,7 +183,7 @@
if config.sections():
return 0, config.sections()
- return 32, config
+ return 2, config
# }}}
def getSections(self, raw=False): # {{{
@@ -235,7 +213,7 @@
reval, option = self.__getOption("Main","version")
- if reval > 2 and reval < 32:
+ if reval > 1 and reval < 2:
raise KeyError(self.ReturnCodes[reval]) # don't tolerate These
if reval > 0:
@@ -266,7 +244,7 @@
reval, clientmode = self.__getOption('Main', 'clientmode')
- if reval > 0 and reval < 64:
+ if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
if reval > 0:
@@ -297,7 +275,7 @@
reval, clientmode = self.__getOption('Main', 'passwordfield')
- if reval > 0 and reval < 64:
+ if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
if reval > 0:
@@ -328,7 +306,7 @@
reval, storetype = self.__getOption('Main', 'storetype')
- if reval > 0 and reval < 64:
+ if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
if reval > 0:
@@ -349,7 +327,7 @@
reval, storetype = self.__getOption('Main', 'file')
- if reval > 0 and reval < 64:
+ if reval > 0 and reval < 4:
raise KeyError(self.ReturnCodes[reval])
if reval > 0:
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2012-09-27 20:53:33 UTC (rev 345)
+++ branches/spd-ng/src/spdCore.py 2012-10-07 14:08:40 UTC (rev 346)
@@ -150,18 +150,16 @@
if __newcolumns == '':
__newcolumns = __newcolumn
else:
- __newcolumns = __newcolumns + ',' + __newcolumn
+ __newcolumns += ',' + __newcolumn
if __columns == '':
__columns = __column
else:
- __columns = __columns + ',' + __column
+ __columns += ',' + __column
# it's not that easy, to delete a column in SQLite
self.dbc.executescript("""
- CREATE TEMPORARY TABLE """ + self.PasswordPreset + """_temp(""" + __newcolumns + """);
- INSERT INTO """ + self.PasswordPreset + """_temp SELECT """ + __columns + """ FROM """ + self.PasswordPreset + """;
- DROP TABLE """ + self.PasswordPreset + """;
+ ALTER TABLE """ + self.PasswordPreset + """ RENAME TO """ + self.PasswordPreset + """_temp;
CREATE TABLE """ + self.PasswordPreset + """(""" + __newcolumns + """);
INSERT INTO """ + self.PasswordPreset + """ SELECT """ + __columns + """ FROM """ + self.PasswordPreset + """_temp;
DROP TABLE """ + self.PasswordPreset + """_temp;
@@ -169,6 +167,37 @@
self.db.commit()
# }}}
+ def renameColumn(self, oldcolumnname, newcolumnname): #{{{
+ __columns = ''
+ __newcolumns = ''
+ for __column in self.getColumns(showid=True):
+ if __column == oldcolumnname and oldcolumnname != '__ID':
+ __newcolumn = newcolumnname + ' text'
+ elif __column == '__ID':
+ __newcolumn = __column + ' INTEGER PRIMARY KEY'
+ else:
+ __newcolumn = __column + ' text'
+
+ if __newcolumns == '':
+ __newcolumns = __newcolumn
+ else:
+ __newcolumns += ',' + __newcolumn
+
+ if __columns == '':
+ __columns = __column
+ else:
+ __columns += ',' + __column
+
+ # it's not that easy, to delete a column in SQLite
+ self.dbc.executescript("""
+ ALTER TABLE """ + self.PasswordPreset + """ RENAME TO """ + self.PasswordPreset + """_temp;
+ CREATE TABLE """ + self.PasswordPreset + """(""" + __newcolumns + """);
+ INSERT INTO """ + self.PasswordPreset + """ SELECT """ + __columns + """ FROM """ + self.PasswordPreset + """_temp;
+ DROP TABLE """ + self.PasswordPreset + """_temp;
+ """)
+ self.db.commit()
+ # }}}
+
def makepass(self,size=16): # {{{
chars = []
chars.extend([i for i in string.ascii_letters])
Modified: branches/spd-ng/src/spdDefaults.py
===================================================================
--- branches/spd-ng/src/spdDefaults.py 2012-09-27 20:53:33 UTC (rev 345)
+++ branches/spd-ng/src/spdDefaults.py 2012-10-07 14:08:40 UTC (rev 346)
@@ -12,18 +12,6 @@
__version__ = '0.3-alpha'
-def __ErrorHandler(function, message): # {{{
- '''ErrorHandler of the Defaults Module.
- # function: the function who called the ErrorHandler
- # message: means the \'Exception\' to throw'''
- print '################################################'
- print 'spdDefaults ErrorHandler.'
- print 'ERRORFUNCTION: ' + function
- print 'ERRORMESSAGE: ' + message
- print '################################################'
- exit(2)
-# }}}
-
def __oldSPDCheck(): # {{{
'''Checks if a old spd configuration file is there and tries to mutate it'''
__oldspdconfig = '~/.spd/spd.conf'
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2012-09-27 20:53:33 UTC (rev 345)
+++ branches/spd-ng/src/spdInterface.py 2012-10-07 14:08:40 UTC (rev 346)
@@ -46,23 +46,23 @@
reval, self.configversion = self.ConfigObject.getConfigVersion(raw=True)
- if reval > 0 and reval < 64:
+ if reval == 1:
spdDefaults.createDefaultConfig(self.ConfigObject)
- return self.__startupCheck()
- elif reval == 64:
+ self.configversion = self.ConfigObject.getConfigVersion()
+ elif reval == 4:
print 'ConfigVersion not found...setting Default one\n'
__blackhole = raw_input('Press any key')
self.ConfigObject.setConfigVersion('0.3-alpha')
self.configversion = self.ConfigObject.getConfigVersion()
- reval, initcheck['clientmode'] = self.ConfigObject.getClientmode(raw=True)
+ if not clientmode:
+ reval, initcheck['clientmode'] = self.ConfigObject.getClientmode(raw=True)
+ if reval == 4:
+ print 'Default Clientmode not found...setting it to CLI\n'
+ __blackhole = raw_input('Press any key')
+ self.ConfigObject.setClientmode('cli')
+ initcheck.update({ 'clientmode' : self.ConfigObject.getClientmode() })
- if reval > 0:
- print 'Clientmode not found...setting it to CLI\n'
- __blackhole = raw_input('Press any key')
- self.ConfigObject.setClientmode('cli')
- initcheck.update({ 'clientmode' : self.ConfigObject.getClientmode() })
-
reval, __passwordfield = self.ConfigObject.getPasswordfield(raw=True)
if reval == 0:
@@ -74,7 +74,7 @@
self.client = __import__('spdInterfaces.' + clientmode.lower(), fromlist=['',])
if 'passwordfield' in initcheck:
- self.client._passwordfield = initcheck['passwordfield']
+ self.client.passwordfield = initcheck['passwordfield']
del initcheck
# }}}
@@ -140,9 +140,25 @@
if column in self.core.getColumns(showid=False):
self.core.delColumn(column)
else:
- raise ValueError('deleteColumn','column ' + column + ' is not part of the passwordfile')
+ raise ValueError('column ' + column + ' is not part of the passwordfile')
# }}}
+ def renameColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+ if len(columns) != 2:
+ raise ValueError('You need to give old and new columnname as argument')
+ else:
+ oldcolumn = columns[0]
+ newcolumn = columns[1]
+ if oldcolumn in self.core.getColumns(showid=False):
+ self.core.renameColumn(oldcolumn, newcolumn)
+ else:
+ raise ValueError('column ' + column + ' is not part of the passwordfile')
+ # }}}
+
def addColumn(self,args): # {{{
if 'args' in args:
columns = args['args']
Modified: branches/spd-ng/src/spdInterfaces/cli.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/cli.py 2012-09-27 20:53:33 UTC (rev 345)
+++ branches/spd-ng/src/spdInterfaces/cli.py 2012-10-07 14:08:40 UTC (rev 346)
@@ -31,7 +31,6 @@
def printPasswords(passdict,args=None): # {{{
"""Print the passwords out of a dictionary.
# passdict: the dictionary full of passwords"""
- __keylength = {}
pwonly = False
if args is not None:
@@ -46,7 +45,7 @@
__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
else:
print passdict[passwordfield][0]
-
+ # print everything line by line
elif __outmode == 'line':
length = 0
for key in passdict.keys():
@@ -63,12 +62,13 @@
else:
print key.ljust(length) + ' : '
print ""
+ # print every entry in one line
elif __outmode == 'wide':
+ __keylength = {}
+ # create a dictionary for all the column lengths
for key in passdict:
- __keylength.update({ key : 0 })
+ __keylength.update({ key : len(key) })
- if len(key) > __keylength[key]:
- __keylength[key] = len(key)
for value in passdict[key]:
if value is not None:
if search('\n',str(value)):
@@ -79,24 +79,33 @@
if len(str(value)) > __keylength[key]:
__keylength[key] = len(str(value))
+ stdout.write(' ' + '__ID'.ljust(__keylength['__ID']) + ' |')
for key in passdict:
- stdout.write(key.ljust(__keylength[key]) + '|')
+ if key != '__ID':
+ stdout.write(' ' + key.ljust(__keylength[key]) + ' |')
stdout.write('\n')
__entries = len(passdict.values()[0])
for i in range(0,__entries):
__space = ''
+
+ # write out the ID first
+ stdout.write(' ' + str(passdict['__ID'][i]).ljust(__keylength['__ID']) + ' |')
+ __space += ''.ljust(__keylength['__ID'],'>') + '>>>'
+ # now comes the rest
for key in passdict:
+ if key == '__ID':
+ continue
if passdict[key][i] is None:
passdict[key][i] = ''
__count = 0
- for line in str(passdict[key][i]).split('\n'):
+ for line in passdict[key][i].split('\n'):
if __count > 0:
stdout.write('\n' + __space)
- stdout.write(line.ljust(__keylength[key]) + '|')
+ stdout.write(' ' + line.ljust(__keylength[key]) + ' |')
__count += 1
- __space = __space + ''.ljust(__keylength[key],'>') + '>'
+ __space += ''.ljust(__keylength[key],'>') + '>>>'
stdout.write('\n')
else:
__ErrorHandler('printPasswords', 'output mode unknown: ' + str(__outmode))
@@ -236,6 +245,12 @@
default = False,
help ="Delete Columns given")
+ group.add_option( "--rename-columns",
+ action = "store_true",
+ dest ="renameColumn",
+ default = False,
+ help ="Rename OLDCOLUMNNAME to NEWCOLUMNNAME")
+
parser.add_option_group(group)
(options, args) = parser.parse_args()
@@ -259,6 +274,8 @@
elif options.deleteColumn:
return [("deleteColumn","saveData"), __optionsdict]
+ elif options.renameColumn:
+ return [("renameColumn","saveData"), __optionsdict]
elif options.addColumn:
return [("addColumn","saveData"), __optionsdict]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-09-27 20:53:40
|
Revision: 345
http://spd.svn.sourceforge.net/spd/?rev=345&view=rev
Author: Z3po
Date: 2012-09-27 20:53:33 +0000 (Thu, 27 Sep 2012)
Log Message:
-----------
finalized plain spdStore module
Modified Paths:
--------------
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/spdInterfaces/cli.py
branches/spd-ng/src/spdStore/devel.py
branches/spd-ng/src/spdStore/plain.py
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2012-09-26 21:58:52 UTC (rev 344)
+++ branches/spd-ng/src/spdCore.py 2012-09-27 20:53:33 UTC (rev 345)
@@ -26,7 +26,7 @@
self.PasswordColumn = ConfigObject.getPasswordfield()
self.PasswordFile = ConfigObject.getPasswordfile()
self.spdStore = __import__('spdStore.' + ConfigObject.getStoretype(), fromlist=['',])
- self.db = self.spdStore.getData(self.PasswordFile)
+ self.db = self.spdStore.getData(self.PasswordFile, self.PasswordPreset)
self.db.row_factory = self.__sql2dict
self.dbc = self.db.cursor()
# }}}
@@ -39,12 +39,16 @@
return result
# }}}
+ def saveData(self): # {{{
+ if self.spdStore != None:
+ self.spdStore.saveData(self.PasswordFile, self.PasswordPreset, self.db)
+ # }}}
+
def searchEntry(self,SearchList,byid=False): # {{{
query = 'select * from ' + self.PasswordPreset + ' where '
- # search by ID
- if byid:
+ if byid: # search by id
for __id in SearchList:
if re.match('\d+',__id):
query += '__ID = ' + __id + ' or '
@@ -55,10 +59,10 @@
# Build the where-clause
for pattern in SearchList:
query += '('
-
for i in self.getColumns():
- if i != self.PasswordColumn:
- query += i + " like '%" + pattern + "%' or "
+ if i != '__ID':
+ if i != self.PasswordColumn:
+ query += i + " like '%" + pattern + "%' or "
query = query[0:-4] + ') and '
query = query[0:-5]
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2012-09-26 21:58:52 UTC (rev 344)
+++ branches/spd-ng/src/spdInterface.py 2012-09-27 20:53:33 UTC (rev 345)
@@ -1,3 +1,4 @@
+#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009
@@ -24,6 +25,7 @@
import spdDefaults
import spdCore
+
class Interface(object): # {{{
"""The Interface Module.
Interface between client and Core."""
@@ -85,7 +87,7 @@
if 'byid' in args:
byid = args['byid']
- if 'args' in args:
+ if 'args' in args and args['args'] != []:
searchString = args['args']
else:
searchString = '%'
@@ -95,14 +97,15 @@
else:
searchlist = string.split(searchString)
- if len(searchlist) == 0:
- searchlist = ['%',]
-
passdict = self.core.searchEntry(searchlist,byid)
return passdict
# }}}
+ def saveData(self, __blackhole='nothing'): # {{{
+ self.core.saveData()
+ # }}}
+
def printPasswords(self,args): # {{{
passdict = self.__findPasswords(args)
self.client.printPasswords(passdict, args)
@@ -114,7 +117,7 @@
if len(__passdict) == 0:
raise ValueError('deleteEntry','No matches found')
- self.client.printPasswords(__passdict)
+ self.client.printPasswords(__passdict, args)
ids = self.client.deleteEntry(__passdict)
self.core.delEntry(ids)
# }}}
@@ -151,13 +154,17 @@
# }}}
def addEntry(self, args): # {{{
- Entry = self.client.createEntry(self.core.getColumns(showid=False))
+ Entry = self.client.addEntry(self.core.getColumns(showid=False))
self.core.addEntry(Entry)
# }}}
def main(self): # {{{
- function, args = self.client.parseArgs(self.core.version)
- getattr(self, function)(args)
+ functions, args = self.client.parseArgs(self.core.version)
+ if type(functions).__name__ == 'tuple':
+ for function in functions:
+ getattr(self, function)(args)
+ else:
+ getattr(self, functions)(args)
# }}}
# }}}
@@ -166,6 +173,5 @@
Iface = Interface()
Iface.main()
-
# EOF
# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4
Modified: branches/spd-ng/src/spdInterfaces/cli.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/cli.py 2012-09-26 21:58:52 UTC (rev 344)
+++ branches/spd-ng/src/spdInterfaces/cli.py 2012-09-27 20:53:33 UTC (rev 345)
@@ -54,14 +54,14 @@
length = len(key)
print ""
for i in range(0,len(passdict.values()[0])):
- print "__ID".ljust(length) + ':' + str(passdict["__ID"][i])
+ 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])
+ print key.ljust(length) + ' : ' + sub('\n','\n ' + ' '.ljust(length),passdict[key][i])
else:
- print key.ljust(length) + ': '
+ print key.ljust(length) + ' : '
print ""
elif __outmode == 'wide':
for key in passdict:
@@ -141,7 +141,7 @@
return __ids
# }}}
-def createEntry(columns): # {{{
+def addEntry(columns): # {{{
Entry = {}
print "Adding a new Entry to our passfile"
for column in columns:
@@ -251,16 +251,16 @@
'pwonly' : options.pwonly })
if options.addEntry:
- return ["addEntry", __optionsdict]
+ return [("addEntry","saveData"), __optionsdict]
elif options.deleteEntry:
- return ["deleteEntry", __optionsdict]
+ return [("deleteEntry","saveData"), __optionsdict]
elif options.editEntry:
- return ["editEntry", __optionsdict]
+ return [("editEntry","saveData"), __optionsdict]
elif options.deleteColumn:
- return ["deleteColumn", __optionsdict]
+ return [("deleteColumn","saveData"), __optionsdict]
elif options.addColumn:
- return ["addColumn", __optionsdict]
+ return [("addColumn","saveData"), __optionsdict]
return ["printPasswords", __optionsdict]
# }}}
Modified: branches/spd-ng/src/spdStore/devel.py
===================================================================
--- branches/spd-ng/src/spdStore/devel.py 2012-09-26 21:58:52 UTC (rev 344)
+++ branches/spd-ng/src/spdStore/devel.py 2012-09-27 20:53:33 UTC (rev 345)
@@ -12,11 +12,11 @@
testdb = '/home/scabrera/Projects/spd/branches/spd-ng/src/test.db'
-def getData(passwordfile): # {{{
+def getData(passwordfile, passwordpreset): # {{{
db = sqlite3.connect(testdb)
return db
# }}}
-def saveData(): # {{{
+def saveData(passwordfile, passwordpreset, database): # {{{
pass
# }}}
Modified: branches/spd-ng/src/spdStore/plain.py
===================================================================
--- branches/spd-ng/src/spdStore/plain.py 2012-09-26 21:58:52 UTC (rev 344)
+++ branches/spd-ng/src/spdStore/plain.py 2012-09-27 20:53:33 UTC (rev 345)
@@ -3,18 +3,39 @@
# Copyright (C) 2009
# Klaus Umbach <tre...@us...>
# Sebastian Cabrera <z3...@us...>
+'''This storage module handles plaintext files seperated by "seperator"'''
import sqlite3
separator = '\t'
-def getData(passwordfile): #{{{
+def getSQLData(passwordpreset, sqlitedb): # {{{
+ sqlitecursor = sqlitedb.cursor()
+
+ query = "pragma Table_info('" + passwordpreset + "')"
+ sqlitecursor.execute(query)
+
+ columns = []
+ for i in sqlitecursor:
+ if i['name'] == "__ID":
+ continue
+ columns.append(str(i['name']))
+
+ query = "SELECT * FROM " + passwordpreset
+ sqlitecursor.execute(query)
+ data = sqlitecursor.fetchall()
+
+ return columns, data
+ # }}}
+
+
+def getData(passwordfile, passwordpreset): #{{{
"""This function reads the password file"""
passfile = open(passwordfile,"r")
sqlitedb = sqlite3.connect(":memory:")
sqlitecursor = sqlitedb.cursor()
- query = "CREATE TABLE passwords ( __ID INTEGER PRIMARY KEY,"
+ query = "CREATE TABLE " + passwordpreset + " ( __ID INTEGER PRIMARY KEY,"
for linecount, i in enumerate(passfile):
line = i.strip('\n').split(separator)
@@ -24,22 +45,46 @@
query += '`' + column + "` TEXT, "
query = query[0:-2] + ' )'
sqlitecursor.execute(query)
- query = "INSERT INTO passwords ( "
+
+ query = "INSERT INTO " + passwordpreset + " ( "
for column in line:
query += column + ', '
- query = query[0:-2] + ' ) VALUES ( '
- next
+ query = query[0:-2] + ' ) VALUES ( \"'
+ continue
inserts = ""
for column in line:
- inserts += column + ', '
- inserts = inserts[0:-2] + ' )'
- print str(query + inserts)
+ inserts += column + '\", \"'
+ inserts = inserts[0:-4] + '\" )'
sqlitecursor.execute(query + inserts)
sqlitedb.commit()
+ passfile.close()
return sqlitedb
#}}}
+def saveData(passwordfile, passwordpreset, sqlitedb): # {{{
+ passfile = open(passwordfile,"w")
+ columns, newdata = getSQLData(passwordpreset, sqlitedb)
+
+ insertdata = ""
+
+ for column in columns:
+ insertdata += str(column) + '\t'
+ insertdata = insertdata[0:-1] + '\n'
+
+ passfile.write(insertdata)
+ insertdata = ""
+
+ for datarow in newdata:
+ for column in columns:
+ insertdata += str(datarow[column]) + '\t'
+ insertdata = insertdata[0:-1] + '\n'
+
+ passfile.write(insertdata)
+
+ passfile.close()
+# }}}
+
# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-09-26 21:59:03
|
Revision: 344
http://spd.svn.sourceforge.net/spd/?rev=344&view=rev
Author: Z3po
Date: 2012-09-26 21:58:52 +0000 (Wed, 26 Sep 2012)
Log Message:
-----------
did some work on spdStore
Modified Paths:
--------------
branches/spd-ng/src/spd
branches/spd-ng/src/spd-cli
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdDefaults.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
Modified: branches/spd-ng/src/spd
===================================================================
--- branches/spd-ng/src/spd 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spd 2012-09-26 21:58:52 UTC (rev 344)
@@ -2,6 +2,5 @@
import spdInterface
-
Interface = spdInterface.Interface()
Interface.main()
Modified: branches/spd-ng/src/spd-cli
===================================================================
--- branches/spd-ng/src/spd-cli 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spd-cli 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,4 +1,6 @@
#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
import spdInterface
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdConfig.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,39 +1,31 @@
-#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
from ConfigParser import RawConfigParser
import os
#import sys
-__version__ = '0.3-alpha'
-
class Config(object): # {{{
'''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' }
+ 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 __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?"""
@@ -222,7 +214,7 @@
reval, config = self.__checkConfigFileReadable()
if reval > 0:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if raw:
return 0, config.sections()
@@ -235,7 +227,7 @@
reval = self.__addSection(section)
if reval > 0:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
# }}}
def getConfigVersion(self, raw=False): # {{{
@@ -244,13 +236,13 @@
reval, option = self.__getOption("Main","version")
if reval > 2 and reval < 32:
- self.__ErrorHandler(self.ReturnCodes[reval]) # don't tolerate These
+ raise KeyError(self.ReturnCodes[reval]) # don't tolerate These
if reval > 0:
if raw:
return reval, None
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if raw:
return reval, option
@@ -265,7 +257,7 @@
reval = self.__setOption("Main","version",version)
if reval > 0:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
# }}}
def getClientmode(self, raw=False): # {{{
@@ -275,13 +267,13 @@
reval, clientmode = self.__getOption('Main', 'clientmode')
if reval > 0 and reval < 64:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if reval > 0:
if raw:
return reval, None
else:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if raw:
return reval, clientmode
@@ -296,7 +288,7 @@
reval = self.__setOption("Main","clientmode",clientmode)
if reval > 0:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
# }}}
def getPasswordfield(self, raw=False): # {{{
@@ -306,13 +298,13 @@
reval, clientmode = self.__getOption('Main', 'passwordfield')
if reval > 0 and reval < 64:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if reval > 0:
if raw:
return reval, None
else:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if raw:
return reval, clientmode
@@ -327,23 +319,23 @@
reval = self.__setOption("Main","passwordfield",passcolumn)
if reval > 0:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
# }}}
- def getStoreType(self, raw=False): # {{{
+ def getStoretype(self, raw=False): # {{{
'''get the clientmode.
# return the clientmode option'''
reval, storetype = self.__getOption('Main', 'storetype')
if reval > 0 and reval < 64:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if reval > 0:
if raw:
return reval, None
else:
- self.__ErrorHandler(self.ReturnCodes[reval])
+ raise KeyError(self.ReturnCodes[reval])
if raw:
return reval, storetype
@@ -351,7 +343,27 @@
return storetype
# }}}
+ def getPasswordfile(self, raw=False): # {{{
+ '''get the password field.
+ # return the password field'''
+ reval, storetype = self.__getOption('Main', 'file')
+
+ if reval > 0 and reval < 64:
+ raise KeyError(self.ReturnCodes[reval])
+
+ if reval > 0:
+ if raw:
+ return reval, None
+ else:
+ raise KeyError(self.ReturnCodes[reval])
+
+ if raw:
+ return reval, storetype
+
+ return storetype
+ # }}}
+
# }}}
# EOF
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdCore.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,3 +1,10 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
+
'''spdCore Module.
Handles the Datastore of SPD.
@@ -3,37 +10,25 @@
Usage:
import spdCore
-coreobject = spdCore.Core()'''
+coreobject = spdCore.Core(ConfigObject)'''
import re
import random
import string
-
class Core(object):
+ version = '0.3-alpha'
+
# create the database from the stuff out of the store
def __init__(self,ConfigObject): # {{{
- self.ConfigSection = ConfigObject.ConfigSection
+ self.PasswordPreset = ConfigObject.ConfigSection
self.PasswordColumn = ConfigObject.getPasswordfield()
- self.spdStore = __import__('spdStore.' + ConfigObject.getStoreType(), fromlist=['',])
- self.db = self.spdStore.getData()
+ self.PasswordFile = ConfigObject.getPasswordfile()
+ self.spdStore = __import__('spdStore.' + ConfigObject.getStoretype(), fromlist=['',])
+ self.db = self.spdStore.getData(self.PasswordFile)
self.db.row_factory = self.__sql2dict
self.dbc = self.db.cursor()
-
- 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 __sql2dict(self,cursor,row): # {{{
result = {}
@@ -42,12 +37,11 @@
result[Column[0]] = row[ColumnNr]
return result
-
# }}}
def searchEntry(self,SearchList,byid=False): # {{{
- query = 'select * from ' + self.ConfigSection + ' where '
+ query = 'select * from ' + self.PasswordPreset + ' where '
# search by ID
if byid:
@@ -55,7 +49,7 @@
if re.match('\d+',__id):
query += '__ID = ' + __id + ' or '
else:
- self.__ErrorHandler('searchEntry', 'Searching for ID but no valid ID given: ' + __id)
+ raise LookupError('Searching for ID but no valid ID given: ' + __id)
query = query[0:-3]
else:
# Build the where-clause
@@ -78,13 +72,13 @@
result[j].append(i[j])
except KeyError:
result[j] = [i[j]]
-
+
return result
# }}}
def addEntry(self,NewDict): # {{{
- query = 'insert into ' + self.ConfigSection + '( '
-
+ query = 'insert into ' + self.PasswordPreset + '( '
+
cols = ''
vals = ''
for i in NewDict.keys():
@@ -98,14 +92,14 @@
def delEntry(self,ID): # {{{
for __id in ID:
- query = 'delete from '+ self.ConfigSection +' where __ID=\'' + str(__id) + '\''
+ query = 'delete from '+ self.PasswordPreset +' where __ID=\'' + str(__id) + '\''
self.dbc.execute(query)
self.db.commit()
# }}}
def editEntry(self,__passdict): # {{{
- query = 'UPDATE ' + self.ConfigSection + ' SET '
+ query = 'UPDATE ' + self.PasswordPreset + ' SET '
for i in range(0, len(__passdict['__ID'])):
for __column in __passdict:
if __column != '__ID':
@@ -113,32 +107,31 @@
query = query[0:-2]
query += ' WHERE __ID = ' + str(__passdict['__ID'][i])
self.dbc.execute(query)
- query = 'UPDATE ' + self.ConfigSection + ' SET '
+ query = 'UPDATE ' + self.PasswordPreset + ' SET '
self.db.commit()
# }}}
def getColumns(self,showid=True): # {{{
- query = "pragma Table_info('" + self.ConfigSection + "')"
+ query = "pragma Table_info('" + self.PasswordPreset + "')"
self.dbc.execute(query)
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'])
+ result.append(i['name'])
return result
# }}}
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 '
+ raise KeyError('Column \"' + columnname + '\" already exists')
+ query='alter table ' + self.PasswordPreset + ' add column ' + columnname + ' text '
self.db.execute(query)
self.db.commit()
# }}}
-
- def delColumn(self,columnname): # {{{
+
+ def delColumn(self,columnname): # {{{
__columns = ''
__newcolumns = ''
for __column in self.getColumns(showid=True):
@@ -162,27 +155,27 @@
# 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;
+ CREATE TEMPORARY TABLE """ + self.PasswordPreset + """_temp(""" + __newcolumns + """);
+ INSERT INTO """ + self.PasswordPreset + """_temp SELECT """ + __columns + """ FROM """ + self.PasswordPreset + """;
+ DROP TABLE """ + self.PasswordPreset + """;
+ CREATE TABLE """ + self.PasswordPreset + """(""" + __newcolumns + """);
+ INSERT INTO """ + self.PasswordPreset + """ SELECT """ + __columns + """ FROM """ + self.PasswordPreset + """_temp;
+ DROP TABLE """ + self.PasswordPreset + """_temp;
""")
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
# }}}
Modified: branches/spd-ng/src/spdDefaults.py
===================================================================
--- branches/spd-ng/src/spdDefaults.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdDefaults.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,3 +1,9 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
"""This is the Defaults Configuration Module
Trying to create the defaults"""
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdInterface.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,3 +1,9 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
'''spdInterface Module.
The Modules handles all the exchange between user and spdCore.
@@ -12,33 +18,32 @@
if building your own interface, name it "whatever" and pass "whatever"
to the Interface Class. The Module must be in spds spdInterfaces path.'''
-from sys import exit
import os
import string
import spdConfig
import spdDefaults
import spdCore
-__version__ = '0.3-alpha'
-
class Interface(object): # {{{
"""The Interface Module.
Interface between client and Core."""
- __spddir = os.path.expanduser('~/.spd/')
- __client = None
- __core = None
+ spddir = os.path.expanduser('~/.spd/')
+ client = None
+ core = None
def __init__(self,clientmode=False): # {{{
"""init procedure"""
initcheck = {}
- if not os.access(self.__spddir, os.F_OK):
- os.mkdir(self.__spddir)
-
self.ConfigObject = spdConfig.Config()
- reval, initcheck['version'] = self.ConfigObject.getConfigVersion(raw=True)
-
+ self.core = spdCore.Core(self.ConfigObject)
+
+ if not os.access(self.spddir, os.F_OK):
+ os.mkdir(self.spddir)
+
+ reval, self.configversion = self.ConfigObject.getConfigVersion(raw=True)
+
if reval > 0 and reval < 64:
spdDefaults.createDefaultConfig(self.ConfigObject)
return self.__startupCheck()
@@ -46,7 +51,7 @@
print 'ConfigVersion not found...setting Default one\n'
__blackhole = raw_input('Press any key')
self.ConfigObject.setConfigVersion('0.3-alpha')
- initcheck.update({ 'version' : self.ConfigObject.getConfigVersion() })
+ self.configversion = self.ConfigObject.getConfigVersion()
reval, initcheck['clientmode'] = self.ConfigObject.getClientmode(raw=True)
@@ -64,21 +69,11 @@
if not clientmode:
clientmode = initcheck['clientmode']
- __tempclient = __import__('spdInterfaces.' + clientmode.lower(), fromlist=['',])
- self.__client = __tempclient
- del __tempclient
+ self.client = __import__('spdInterfaces.' + clientmode.lower(), fromlist=['',])
if 'passwordfield' in initcheck:
- self.__client._passwordfield = initcheck['passwordfield']
+ self.client._passwordfield = initcheck['passwordfield']
-
- self.__core = spdCore.Core(self.ConfigObject)
-
- self.__version = { 'ConfigFile' : initcheck['version'],
- 'spdInterface' : __version__,
- 'spdDefaults' : spdDefaults.__version__,
- 'spdConfig' : spdConfig.__version__ }
-
del initcheck
# }}}
@@ -103,14 +98,14 @@
if len(searchlist) == 0:
searchlist = ['%',]
- passdict = self.__core.searchEntry(searchlist,byid)
+ passdict = self.core.searchEntry(searchlist,byid)
return passdict
# }}}
def printPasswords(self,args): # {{{
passdict = self.__findPasswords(args)
- self.__client.printPasswords(passdict, args)
+ self.client.printPasswords(passdict, args)
# }}}
def deleteEntry(self, args): # {{{
@@ -119,16 +114,16 @@
if len(__passdict) == 0:
raise ValueError('deleteEntry','No matches found')
- self.__client.printPasswords(__passdict)
- ids = self.__client.deleteEntry(__passdict)
- self.__core.delEntry(ids)
+ self.client.printPasswords(__passdict)
+ ids = self.client.deleteEntry(__passdict)
+ self.core.delEntry(ids)
# }}}
def editEntry(self,args): # {{{
__passdict = self.__findPasswords(args)
if len(__passdict) > 0:
- __newpassdict = self.__client.editEntry(__passdict)
- self.__core.editEntry(__newpassdict)
+ __newpassdict = self.client.editEntry(__passdict)
+ self.core.editEntry(__newpassdict)
else:
raise ValueError('no matches for ' + str(args["args"]) + 'found')
# }}}
@@ -139,8 +134,8 @@
else:
columns = []
for column in columns:
- if column in self.__core.getColumns(showid=False):
- self.__core.delColumn(column)
+ if column in self.core.getColumns(showid=False):
+ self.core.delColumn(column)
else:
raise ValueError('deleteColumn','column ' + column + ' is not part of the passwordfile')
# }}}
@@ -152,16 +147,16 @@
columns = []
for column in columns:
- self.__core.addColumn(column)
+ self.core.addColumn(column)
# }}}
def addEntry(self, args): # {{{
- Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
- self.__core.addEntry(Entry)
+ Entry = self.client.createEntry(self.core.getColumns(showid=False))
+ self.core.addEntry(Entry)
# }}}
def main(self): # {{{
- function, args = self.__client.parseArgs(self.__version)
+ function, args = self.client.parseArgs(self.core.version)
getattr(self, function)(args)
# }}}
Modified: branches/spd-ng/src/spdInterfaces/__init__.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/__init__.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdInterfaces/__init__.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,4 +1,9 @@
# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
'''spdInterfaces Module
This Module takes Care of the Interface used by SPD.'''
Modified: branches/spd-ng/src/spdInterfaces/cli.py
===================================================================
--- branches/spd-ng/src/spdInterfaces/cli.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdInterfaces/cli.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,3 +1,9 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
"""Client Interfaces Module
This is the Cli Module.
@@ -8,7 +14,6 @@
from sys import stdout
from re import sub, search
-__version__ = '0.3-alpha'
passwordfield = 'Password'
def __ErrorHandler(function,message): # {{{
@@ -153,16 +158,12 @@
return Entry
# }}}
-def parseArgs(versions): # {{{
+def parseArgs(coreversion): # {{{
__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__,
+ version = coreversion,
epilog = """With no parameters it will print out everything!
Please report Bugs or Feature Request at http://spd.sourceforge.net""")
Modified: branches/spd-ng/src/spdStore/__init__.py
===================================================================
--- branches/spd-ng/src/spdStore/__init__.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdStore/__init__.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,3 +1,9 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
'''spdStore Module
This Modules takes Care of the storage Engine used by SPD.'''
Modified: branches/spd-ng/src/spdStore/devel.py
===================================================================
--- branches/spd-ng/src/spdStore/devel.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdStore/devel.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,4 +1,9 @@
# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
+
'''spdStore.devel
This module is just for development. No real data should be written into that database'''
@@ -7,7 +12,7 @@
testdb = '/home/scabrera/Projects/spd/branches/spd-ng/src/test.db'
-def getData(): # {{{
+def getData(passwordfile): # {{{
db = sqlite3.connect(testdb)
return db
# }}}
Modified: branches/spd-ng/src/spdStore/plain.py
===================================================================
--- branches/spd-ng/src/spdStore/plain.py 2012-09-24 21:12:21 UTC (rev 343)
+++ branches/spd-ng/src/spdStore/plain.py 2012-09-26 21:58:52 UTC (rev 344)
@@ -1,5 +1,45 @@
# -*- coding: utf-8 -*-
#
+# Copyright (C) 2009
+# Klaus Umbach <tre...@us...>
+# Sebastian Cabrera <z3...@us...>
-pass
+import sqlite3
+
+separator = '\t'
+
+def getData(passwordfile): #{{{
+ """This function reads the password file"""
+
+ passfile = open(passwordfile,"r")
+ sqlitedb = sqlite3.connect(":memory:")
+ sqlitecursor = sqlitedb.cursor()
+ query = "CREATE TABLE passwords ( __ID INTEGER PRIMARY KEY,"
+
+ for linecount, i in enumerate(passfile):
+ line = i.strip('\n').split(separator)
+
+ if linecount == 0: # the first line defines the collumns
+ for column in line:
+ query += '`' + column + "` TEXT, "
+ query = query[0:-2] + ' )'
+ sqlitecursor.execute(query)
+ query = "INSERT INTO passwords ( "
+ for column in line:
+ query += column + ', '
+ query = query[0:-2] + ' ) VALUES ( '
+ next
+
+ inserts = ""
+ for column in line:
+ inserts += column + ', '
+ inserts = inserts[0:-2] + ' )'
+ print str(query + inserts)
+ sqlitecursor.execute(query + inserts)
+
+ sqlitedb.commit()
+
+ return sqlitedb
+#}}}
+
# 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.
|
|
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.
|
|
From: <Z3...@us...> - 2012-09-23 21:14:08
|
Revision: 342
http://spd.svn.sourceforge.net/spd/?rev=342&view=rev
Author: Z3po
Date: 2012-09-23 21:13:56 +0000 (Sun, 23 Sep 2012)
Log Message:
-----------
Sorry for the broken checkin...I'm doing some work currently to implement different spdStore types.
Modified Paths:
--------------
branches/spd-ng/src/Interfaces/cli.py
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdInterface.py
Added Paths:
-----------
branches/spd-ng/src/spdStore/devel.py
branches/spd-ng/src/spdStore/plain.py
Modified: branches/spd-ng/src/Interfaces/cli.py
===================================================================
--- branches/spd-ng/src/Interfaces/cli.py 2012-09-13 12:02:44 UTC (rev 341)
+++ branches/spd-ng/src/Interfaces/cli.py 2012-09-23 21:13:56 UTC (rev 342)
@@ -158,8 +158,7 @@
parser = OptionParser( "%prog [Options] [Keywords]",
description = "SPD - Simple Password Displayer - CLI",
- version = """spdCore """ + versions['spdCore'] +
- """\nspdInterface """ + versions['spdInterface'] +
+ version = """\nspdInterface """ + versions['spdInterface'] +
"""\nspdConfig """ + versions['spdConfig'] +
"""\nspdDefaults """ + versions['spdDefaults'] +
"""\nConfigFile """ + versions['ConfigFile'] +
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2012-09-13 12:02:44 UTC (rev 341)
+++ branches/spd-ng/src/spdConfig.py 2012-09-23 21:13:56 UTC (rev 342)
@@ -330,6 +330,28 @@
self.__ErrorHandler(self.ReturnCodes[reval])
# }}}
+ def getStoreType(self, raw=False): # {{{
+ '''get the clientmode.
+ # return the clientmode option'''
+
+ reval, storetype = self.__getOption('Main', 'storetype')
+
+ 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 raw:
+ return reval, storetype
+
+ return storetype
+ # }}}
+
+
# }}}
# EOF
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2012-09-13 12:02:44 UTC (rev 341)
+++ branches/spd-ng/src/spdCore.py 2012-09-23 21:13:56 UTC (rev 342)
@@ -9,9 +9,6 @@
import re
import random
import string
-#import spdConfig
-import spdStore
-__version__ = '0.3-alpha'
class Core(object):
@@ -20,7 +17,8 @@
def __init__(self,ConfigObject): # {{{
self.ConfigSection = ConfigObject.ConfigSection
self.PasswordColumn = ConfigObject.getPasswordfield()
- self.db = sqlite3.connect('test.db')
+ self.storeType = __import__('spdStore.' + ConfigObject.getStoreType())
+ self.db = sqlite3.connect(':memory:')
self.db.row_factory = self.__sql2dict
self.dbc = self.db.cursor()
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2012-09-13 12:02:44 UTC (rev 341)
+++ branches/spd-ng/src/spdInterface.py 2012-09-23 21:13:56 UTC (rev 342)
@@ -15,188 +15,162 @@
from sys import exit
import os
import string
+import spdConfig
+import spdDefaults
+import spdCore
-try:
- import spdConfig
- import spdDefaults
- import spdCore
-except ImportError:
- print '##### ERROR #####'
- print 'spdInterface: spd not installed. Missing Modules.'
- exit(2)
-
__version__ = '0.3-alpha'
class Interface(object): # {{{
- """The Interface Module.
- Interface between client and Core."""
- __spddir = os.path.expanduser('~/.spd/')
- __client = None
- __core = None
+ """The Interface Module.
+ Interface between client and Core."""
+ __spddir = os.path.expanduser('~/.spd/')
+ __client = None
+ __core = None
- def __init__(self,clientmode=False): # {{{
- """init procedure"""
- initcheck = {}
+ def __init__(self,clientmode=False): # {{{
+ """init procedure"""
+ initcheck = {}
- if not os.access(self.__spddir, os.F_OK):
- try:
- os.mkdir(self.__spddir)
- except Exception, e:
- self.__ErrorHandler('__init__','Could not create ' + self.__spddir + ' Exception: ' + str(e))
-
- __config = spdConfig.Config()
+ if not os.access(self.__spddir, os.F_OK):
+ os.mkdir(self.__spddir)
+
+ __config = spdConfig.Config()
- reval, initcheck['version'] = __config.getConfigVersion(raw=True)
-
- if reval > 0 and reval < 64:
- spdDefaults.createDefaultConfig(__config)
- 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() })
+ reval, initcheck['version'] = __config.getConfigVersion(raw=True)
+
+ if reval > 0 and reval < 64:
+ spdDefaults.createDefaultConfig(__config)
+ 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() })
- reval, initcheck['clientmode'] = __config.getClientmode(raw=True)
+ reval, initcheck['clientmode'] = __config.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() })
+ 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() })
- reval, __passwordfield = __config.getPasswordfield(raw=True)
+ reval, __passwordfield = __config.getPasswordfield(raw=True)
- if reval == 0:
- initcheck.update({ 'passwordfield' : __passwordfield })
+ if reval == 0:
+ initcheck.update({ 'passwordfield' : __passwordfield })
+ if not clientmode:
+ clientmode = initcheck['clientmode']
- if not clientmode:
- clientmode = initcheck['clientmode']
+ __tempclient = __import__('Interfaces.' + clientmode.lower())
+ self.__client = __tempclient.cli
+ del __tempclient
- try:
- __tempclient = __import__('Interfaces.' + clientmode.lower())
- except ImportError:
- self.__ErrorHandler('__init__', 'clientmode ' + clientmode + ' not available!')
- else:
- self.__client = __tempclient.cli
- del __tempclient
+ if 'passwordfield' in initcheck:
+ self.__client._passwordfield = initcheck['passwordfield']
- if 'passwordfield' in initcheck:
- self.__client._passwordfield = initcheck['passwordfield']
+ self.__core = spdCore.Core(__config)
- self.__core = spdCore.Core(__config)
+ self.__version = { 'ConfigFile' : initcheck['version'],
+ 'spdInterface' : __version__,
+ 'spdDefaults' : spdDefaults.__version__,
+ 'spdConfig' : spdConfig.__version__ }
- self.__version = { 'ConfigFile' : initcheck['version'],
- 'spdCore' : spdCore.__version__,
- 'spdInterface' : __version__,
- 'spdDefaults' : spdDefaults.__version__,
- 'spdConfig' : spdConfig.__version__ }
+ del initcheck
+ # }}}
- del initcheck
- # }}}
+ def __findPasswords(self,args): # {{{
+ """Find the passwords by searchlist/searchstring handed.
+ print the results in CLIENTMODE.
+ # searchlist: optional string or list of keywords to search for."""
- def __ErrorHandler(self,function,message): # {{{
- """ErrorHandler of the Interface Module.
- # message: means the \'Exception\' to throw"""
- print "################################################"
- print "spdInterface ErrorHandler."
- print "ERRORFUNCTION: " + function
- print "ERRORMESSAGE: " + message
- print "################################################"
- exit(2)
- # }}}
+ if 'byid' in args:
+ byid = args['byid']
+
+ if 'args' in args:
+ searchString = args['args']
+ else:
+ searchString = '%'
- def __findPasswords(self,args): # {{{
- """Find the passwords by searchlist/searchstring handed.
- print the results in CLIENTMODE.
- # searchlist: optional string or list of keywords to search for."""
+ if type(searchString).__name__ == 'list':
+ searchlist = searchString
+ else:
+ searchlist = string.split(searchString)
- if 'byid' in args:
- byid = args['byid']
-
- if 'args' in args:
- searchString = args['args']
- else:
- searchString = '%'
+ if len(searchlist) == 0:
+ searchlist = ['%',]
- if type(searchString).__name__ == 'list':
- searchlist = searchString
- else:
- searchlist = string.split(searchString)
+ passdict = self.__core.searchEntry(searchlist,byid)
- if len(searchlist) == 0:
- searchlist = ['%',]
+ return passdict
+ # }}}
- passdict = self.__core.searchEntry(searchlist,byid)
+ def printPasswords(self,args): # {{{
+ passdict = self.__findPasswords(args)
+ self.__client.printPasswords(passdict, args)
+ # }}}
- return passdict
- # }}}
+ def deleteEntry(self, args): # {{{
+ __passdict = self.__findPasswords(args)
+
+ if len(__passdict) == 0:
+ raise ValueError('deleteEntry','No matches found')
- def printPasswords(self,args): # {{{
- passdict = self.__findPasswords(args)
- self.__client.printPasswords(passdict, args)
- # }}}
+ self.__client.printPasswords(__passdict)
+ ids = self.__client.deleteEntry(__passdict)
+ self.__core.delEntry(ids)
+ # }}}
- def deleteEntry(self, args): # {{{
- __passdict = self.__findPasswords(args)
-
- if len(__passdict) == 0:
- self.__ErrorHandler('deleteEntry','No matches found')
+ def editEntry(self,args): # {{{
+ __passdict = self.__findPasswords(args)
+ if len(__passdict) > 0:
+ __newpassdict = self.__client.editEntry(__passdict)
+ self.__core.editEntry(__newpassdict)
+ else:
+ raise ValueError('no matches for ' + str(args["args"]) + 'found')
+ # }}}
- self.__client.printPasswords(__passdict)
- ids = self.__client.deleteEntry(__passdict)
- self.__core.delEntry(ids)
- # }}}
+ def deleteColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+ for column in columns:
+ if column in self.__core.getColumns(showid=False):
+ self.__core.delColumn(column)
+ else:
+ raise ValueError('deleteColumn','column ' + column + ' is not part of the passwordfile')
+ # }}}
- def editEntry(self,args): # {{{
- __passdict = self.__findPasswords(args)
- if len(__passdict) > 0:
- __newpassdict = self.__client.editEntry(__passdict)
- self.__core.editEntry(__newpassdict)
- else:
- self.__ErrorHandler('editEntry','no matches for ' + str(args["args"]) + 'found')
- # }}}
+ def addColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
- def deleteColumn(self,args): # {{{
- if 'args' in args:
- columns = args['args']
- else:
- columns = []
- for column in columns:
- if column in self.__core.getColumns(showid=False):
- self.__core.delColumn(column)
- else:
- self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
- # }}}
+ for column in columns:
+ self.__core.addColumn(column)
+ # }}}
- def addColumn(self,args): # {{{
- if 'args' in args:
- columns = args['args']
- else:
- columns = []
+ def addEntry(self, args): # {{{
+ Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
+ self.__core.addEntry(Entry)
+ # }}}
- for column in columns:
- self.__core.addColumn(column)
- # }}}
+ def main(self): # {{{
+ function, args = self.__client.parseArgs(self.__version)
+ getattr(self, function)(args)
+ # }}}
- def addEntry(self, args): # {{{
- Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
- self.__core.addEntry(Entry)
- # }}}
-
- def main(self): # {{{
- function, args = self.__client.parseArgs(self.__version)
- getattr(self, function)(args)
- # }}}
-
# }}}
if __name__ == '__main__':
- Iface = Interface()
- Iface.main()
+ Iface = Interface()
+ Iface.main()
# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
+# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4
Added: branches/spd-ng/src/spdStore/devel.py
===================================================================
--- branches/spd-ng/src/spdStore/devel.py (rev 0)
+++ branches/spd-ng/src/spdStore/devel.py 2012-09-23 21:13:56 UTC (rev 342)
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+#
+
+import sqlite3
+
+testdb = '/home/scabrera/Projects/spd/branches/spd-ng/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)
+
+
Property changes on: branches/spd-ng/src/spdStore/devel.py
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Rev URL
Added: svn:eol-style
+ native
Added: branches/spd-ng/src/spdStore/plain.py
===================================================================
--- branches/spd-ng/src/spdStore/plain.py (rev 0)
+++ branches/spd-ng/src/spdStore/plain.py 2012-09-23 21:13:56 UTC (rev 342)
@@ -0,0 +1,4 @@
+# -*- coding: utf-8 -*-
+#
+
+pass
Property changes on: branches/spd-ng/src/spdStore/plain.py
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Rev URL
Added: svn:eol-style
+ native
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-09-13 12:02:55
|
Revision: 341
http://spd.svn.sourceforge.net/spd/?rev=341&view=rev
Author: Z3po
Date: 2012-09-13 12:02:44 +0000 (Thu, 13 Sep 2012)
Log Message:
-----------
fixed format of files and fixed delete call in spd-cli
Modified Paths:
--------------
trunk/src/spd-cli
Modified: trunk/src/spd-cli
===================================================================
--- trunk/src/spd-cli 2012-08-06 13:38:18 UTC (rev 340)
+++ trunk/src/spd-cli 2012-09-13 12:02:44 UTC (rev 341)
@@ -30,63 +30,65 @@
pp = spdCore.name(sys.argv[0])
# {{{ OptionParser stuff
-parser = OptionParser( "%prog [Options] Search",
- description = pp.acronym + ' - ' + pp.name,
- version = version,
- epilog = "With no parameters it will print out everything!")
+parser = OptionParser( "%prog [Options] Search",
+ description = pp.acronym + ' - ' + pp.name,
+ version = version,
+ epilog = "With no parameters it will print out everything!")
-parser.add_option( "-d", "--delete",
- metavar="Keywords",
- dest ="delete",
- help ="Entries to delete")
+parser.add_option( "-d", "--delete",
+ action="store_true",
+ metavar="Keywords",
+ dest ="delete",
+ default=False,
+ help ="Entries to delete")
-parser.add_option( "-e", "--edit",
- metavar="ID",
- dest ="edit",
- help ="ID to edit")
+parser.add_option( "-e", "--edit",
+ metavar="ID",
+ dest ="edit",
+ help ="ID to edit")
-parser.add_option( "-i", "--delete-id",
- metavar="ID",
- dest ="deleteID",
- help ="ID to delete")
+parser.add_option( "-i", "--delete-id",
+ metavar="ID",
+ dest ="deleteID",
+ help ="ID to delete")
-parser.add_option( "--id",
- dest ="id",
- help ="Show Password by ID")
+parser.add_option( "--id",
+ dest ="id",
+ help ="Show Password by ID")
-parser.add_option( "-a", "--add",
- action="store_true",
- dest = "add",
- default=False,
- help = "Add an Entry")
+parser.add_option( "-a", "--add",
+ action="store_true",
+ dest = "add",
+ default=False,
+ help = "Add an Entry")
-parser.add_option( "--add-collumn",
- metavar="Collumn",
- dest = "addcollumn",
- default=False,
- help = "Add a Collumn to Passfile")
+parser.add_option( "--add-collumn",
+ metavar="Collumn",
+ dest = "addcollumn",
+ default=False,
+ help = "Add a Collumn to Passfile")
-parser.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( "-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( "-w", "--wide",
- action="store_true",
- dest = "widemode",
- default=False,
- help = "print output in wide mode (means as a table)")
+parser.add_option( "-w", "--wide",
+ action="store_true",
+ dest = "widemode",
+ default=False,
+ help = "print output in wide mode (means as a table)")
-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( "-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( "--passfile",
+ dest = "passfile",
+ help = "do not use the confgured passfile but the one given here")
(options, args) = parser.parse_args()
# }}}
@@ -98,53 +100,53 @@
# check if it is a search or not.
if options.add:
- pc.addEntry(interface.newEntry(pc.getCollumns()))
- pc.exportPasswordsPlain()
+ pc.addEntry(interface.newEntry(pc.getCollumns()))
+ pc.exportPasswordsPlain()
elif options.edit:
- updates = interface.editEntry(pc.findPassword(options.edit,id=True))
- pc.updateEntry(updates)
- pc.exportPasswordsPlain()
+ updates = interface.editEntry(pc.findPassword(options.edit,id=True))
+ pc.updateEntry(updates)
+ pc.exportPasswordsPlain()
elif options.addcollumn:
- pc.addCollumn(options.addcollumn)
- pc.exportPasswordsPlain()
+ pc.addCollumn(options.addcollumn)
+ pc.exportPasswordsPlain()
elif options.delete:
- searchPatterns = args
- pc.delEntry(searchPatterns)
- pc.exportPasswordsPlain()
+ searchPatterns = args
+ pc.delEntry(searchPatterns)
+ pc.exportPasswordsPlain()
elif options.deleteID:
- id = options.deleteID
- pc.delEntry('nix', id=id)
- pc.exportPasswordsPlain()
+ id = options.deleteID
+ pc.delEntry('nix', id=id)
+ pc.exportPasswordsPlain()
elif options.pwonly:
- searchPatterns = args
- try:
- if options.id:
- print pc.findPassword(options.id,id=True)[pc.passwordField][0]
- else:
- print pc.findPassword(searchPatterns)[pc.passwordField][0]
- except:
- pass
+ searchPatterns = args
+ try:
+ if options.id:
+ print pc.findPassword(options.id,id=True)[pc.passwordField][0]
+ else:
+ print pc.findPassword(searchPatterns)[pc.passwordField][0]
+ except:
+ pass
elif options.widemode:
- searchPatterns = args
- if options.id:
- interface.tableOutput(pc.findPassword(options.id,id=True))
- else:
- interface.tableOutput(pc.findPassword(searchPatterns))
+ searchPatterns = args
+ if options.id:
+ interface.tableOutput(pc.findPassword(options.id,id=True))
+ else:
+ interface.tableOutput(pc.findPassword(searchPatterns))
else: # regular search
- searchPatterns = args
- if options.id:
- interface.listOutput(pc.findPassword(options.id,id=True))
- else:
- interface.listOutput(pc.findPassword(searchPatterns))
+ searchPatterns = args
+ if options.id:
+ interface.listOutput(pc.findPassword(options.id,id=True))
+ else:
+ interface.listOutput(pc.findPassword(searchPatterns))
# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
+# vim:filetype=python:foldmethod=marker:autoindent:expandtab:tabstop=4
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-08-06 13:38:24
|
Revision: 340
http://spd.svn.sourceforge.net/spd/?rev=340&view=rev
Author: Z3po
Date: 2012-08-06 13:38:18 +0000 (Mon, 06 Aug 2012)
Log Message:
-----------
added missing init.py to Interfaces directory (so importing works)
Added Paths:
-----------
branches/spd-ng/src/Interfaces/__init__.py
Property changes on: branches/spd-ng/src/Interfaces/__init__.py
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Rev URL
Added: svn:eol-style
+ native
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2012-06-07 20:46:36
|
Revision: 339
http://spd.svn.sourceforge.net/spd/?rev=339&view=rev
Author: Z3po
Date: 2012-06-07 20:46:30 +0000 (Thu, 07 Jun 2012)
Log Message:
-----------
I just quick-fixed the work-in-progress. I need to continue with spd-ng once i get the time *being ashamed*
Modified Paths:
--------------
branches/spd-ng/src/spdConfig.py
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2011-06-28 21:24:35 UTC (rev 338)
+++ branches/spd-ng/src/spdConfig.py 2012-06-07 20:46:30 UTC (rev 339)
@@ -10,7 +10,6 @@
'''This is the Configuration Module
You can read or set config options'''
__configfile = None
- ConfigSection = 'Main'
ReturnCodes = { 2 : 'Missing ConfigFile',
4 : 'ConfigFile not Readable',
@@ -18,6 +17,7 @@
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)
@@ -203,7 +203,17 @@
return reval
return 0
+ # }}}
+ def getAllSections(self): # {{{
+ reval, config = self.__checkConfigFileReadable()
+ if reval > 0:
+ return reval, config
+
+ if config.sections():
+ return 0, config.sections()
+
+ return 32, config
# }}}
def getSections(self, raw=False): # {{{
@@ -226,7 +236,6 @@
if reval > 0:
self.__ErrorHandler(self.ReturnCodes[reval])
-
# }}}
def getConfigVersion(self, raw=False): # {{{
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-06-28 21:24:42
|
Revision: 338
http://spd.svn.sourceforge.net/spd/?rev=338&view=rev
Author: Z3po
Date: 2011-06-28 21:24:35 +0000 (Tue, 28 Jun 2011)
Log Message:
-----------
minor cleanup
Modified Paths:
--------------
branches/spd-ng/src/Interfaces/cli.py
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/spdStore/__init__.py
Modified: branches/spd-ng/src/Interfaces/cli.py
===================================================================
--- branches/spd-ng/src/Interfaces/cli.py 2011-06-28 20:24:22 UTC (rev 337)
+++ branches/spd-ng/src/Interfaces/cli.py 2011-06-28 21:24:35 UTC (rev 338)
@@ -9,7 +9,7 @@
from re import sub, search
__version__ = '0.3-alpha'
-_passwordfield = 'Password'
+passwordfield = 'Password'
def __ErrorHandler(function,message): # {{{
"""ErrorHandler of the Client Module.
@@ -40,7 +40,7 @@
if len(passdict['__ID']) > 1:
__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
else:
- print passdict[_passwordfield][0]
+ print passdict[passwordfield][0]
elif __outmode == 'line':
length = 0
@@ -153,13 +153,17 @@
return Entry
# }}}
-def parseArgs(version): # {{{
+def parseArgs(versions): # {{{
__optionsdict = {}
parser = OptionParser( "%prog [Options] [Keywords]",
description = "SPD - Simple Password Displayer - CLI",
- version = """spdCore """ + version +
- """\nspdCLI """ + __version__,
+ version = """spdCore """ + versions['spdCore'] +
+ """\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""")
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2011-06-28 20:24:22 UTC (rev 337)
+++ branches/spd-ng/src/spdConfig.py 2011-06-28 21:24:35 UTC (rev 338)
@@ -10,6 +10,7 @@
'''This is the Configuration Module
You can read or set config options'''
__configfile = None
+ ConfigSection = 'Main'
ReturnCodes = { 2 : 'Missing ConfigFile',
4 : 'ConfigFile not Readable',
@@ -323,4 +324,4 @@
# }}}
# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
+# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2011-06-28 20:24:22 UTC (rev 337)
+++ branches/spd-ng/src/spdCore.py 2011-06-28 21:24:35 UTC (rev 338)
@@ -17,9 +17,9 @@
class Core(object):
# create the database from the stuff out of the store
- def __init__(self,ConfigSection='Main',PasswordColumn='Password'): # {{{
- self.ConfigSection = ConfigSection
- self.PasswordColumn = PasswordColumn
+ def __init__(self,ConfigObject): # {{{
+ self.ConfigSection = ConfigObject.ConfigSection
+ self.PasswordColumn = ConfigObject.getPasswordfield()
self.db = sqlite3.connect('test.db')
self.db.row_factory = self.__sql2dict
self.dbc = self.db.cursor()
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2011-06-28 20:24:22 UTC (rev 337)
+++ branches/spd-ng/src/spdInterface.py 2011-06-28 21:24:35 UTC (rev 338)
@@ -9,8 +9,8 @@
or force a clientmode with:
Interface = spdInterface.Interface('CLI')
-if building your own interface, name it spd"whatever" and pass "whatever"
-to the Interface Class. The Module must be in pythons include path.'''
+if building your own interface, name it "whatever" and pass "whatever"
+to the Interface Class. The Module must be in spds Interfaces path.'''
from sys import exit
import os
@@ -31,17 +31,46 @@
"""The Interface Module.
Interface between client and Core."""
__spddir = os.path.expanduser('~/.spd/')
- __version = None
__client = None
__core = None
def __init__(self,clientmode=False): # {{{
"""init procedure"""
+ initcheck = {}
- initcheck = self.__startupCheck()
+ if not os.access(self.__spddir, os.F_OK):
+ try:
+ os.mkdir(self.__spddir)
+ except Exception, e:
+ self.__ErrorHandler('__init__','Could not create ' + self.__spddir + ' Exception: ' + str(e))
+
+ __config = spdConfig.Config()
- self.__version = initcheck['version']
+ reval, initcheck['version'] = __config.getConfigVersion(raw=True)
+
+ if reval > 0 and reval < 64:
+ spdDefaults.createDefaultConfig(__config)
+ 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() })
+ reval, initcheck['clientmode'] = __config.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() })
+
+ reval, __passwordfield = __config.getPasswordfield(raw=True)
+
+ if reval == 0:
+ initcheck.update({ 'passwordfield' : __passwordfield })
+
+
if not clientmode:
clientmode = initcheck['clientmode']
@@ -56,9 +85,16 @@
if 'passwordfield' in initcheck:
self.__client._passwordfield = initcheck['passwordfield']
+
+ self.__core = spdCore.Core(__config)
+
+ self.__version = { 'ConfigFile' : initcheck['version'],
+ 'spdCore' : spdCore.__version__,
+ 'spdInterface' : __version__,
+ 'spdDefaults' : spdDefaults.__version__,
+ 'spdConfig' : spdConfig.__version__ }
+
del initcheck
-
- self.__core = spdCore.Core(ConfigSection='Main')
# }}}
def __ErrorHandler(self,function,message): # {{{
@@ -72,45 +108,6 @@
exit(2)
# }}}
- def __startupCheck(self): # {{{
- """Do initial checks"""
- __initargs = {}
-
- if not os.access(self.__spddir, os.F_OK):
- try:
- os.mkdir(self.__spddir)
- except Exception, e:
- self.__ErrorHandler('__startupCheck','Could not create ' + self.__spddir + ' Exception: ' + str(e))
-
- __config = spdConfig.Config()
-
- reval, __initargs['version'] = __config.getConfigVersion(raw=True)
-
- if reval > 0 and reval < 64:
- spdDefaults.createDefaultConfig(__config)
- 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')
- __initargs.update({ 'version' : __config.getConfigVersion() })
-
- reval, __initargs['clientmode'] = __config.getClientmode(raw=True)
-
- if reval > 0:
- print 'Clientmode not found...setting it to CLI\n'
- __input = raw_input('Press any key')
- __config.setClientmode('CLI')
- __initargs.update({ 'clientmode' : __config.getClientmode() })
-
- reval, __passwordfield = __config.getPasswordfield(raw=True)
-
- if reval == 0:
- __initargs.update({ 'passwordfield' : __passwordfield })
-
- return(__initargs)
- # }}}
-
def __findPasswords(self,args): # {{{
"""Find the passwords by searchlist/searchstring handed.
print the results in CLIENTMODE.
@@ -196,6 +193,10 @@
# }}}
+if __name__ == '__main__':
+ Iface = Interface()
+ Iface.main()
+
# EOF
# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
Modified: branches/spd-ng/src/spdStore/__init__.py
===================================================================
--- branches/spd-ng/src/spdStore/__init__.py 2011-06-28 20:24:22 UTC (rev 337)
+++ branches/spd-ng/src/spdStore/__init__.py 2011-06-28 21:24:35 UTC (rev 338)
@@ -1,10 +1,9 @@
'''spdStore Module
-This Module takes Care of the storage Engine used by SPD.
+This Modules takes Care of the storage Engine used by SPD.
Currently Implemented Storage Types are
- plain
-- gpg
-Call the Store() Class with supplying the used storage type'''
+- gpg'''
# EOF
# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-06-28 20:24:29
|
Revision: 337
http://spd.svn.sourceforge.net/spd/?rev=337&view=rev
Author: Z3po
Date: 2011-06-28 20:24:22 +0000 (Tue, 28 Jun 2011)
Log Message:
-----------
think i found the right structure :)
Modified Paths:
--------------
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/test.db
Added Paths:
-----------
branches/spd-ng/src/Interfaces/
branches/spd-ng/src/Interfaces/cli.py
branches/spd-ng/src/spdInterface.py
Removed Paths:
-------------
branches/spd-ng/src/Interfaces/__init__.py
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdInterface/
Deleted: branches/spd-ng/src/Interfaces/__init__.py
===================================================================
--- branches/spd-ng/src/spdInterface/__init__.py 2011-06-27 20:31:22 UTC (rev 336)
+++ branches/spd-ng/src/Interfaces/__init__.py 2011-06-28 20:24:22 UTC (rev 337)
@@ -1,201 +0,0 @@
-'''spdInterface Module.
-
-The Modules handles all the exchange between user and spdCore.
-Usage:
- import spdInterface
- Interface = spdInterface.Interface()
- Interface.main()
-
-or force a clientmode with:
- Interface = spdInterface.Interface('CLI')
-
-if building your own interface, name it spd"whatever" and pass "whatever"
-to the Interface Class. The Module must be in pythons include path.'''
-
-from sys import exit
-import os
-import string
-
-try:
- import spdConfig
- import spdDefaults
- import spdCore
-except ImportError:
- print '##### ERROR #####'
- print 'spdInterface: spd not installed. Missing Modules.'
- exit(2)
-
-__version__ = '0.3-alpha'
-
-class Interface(object): # {{{
- """The Interface Module.
- Interface between client and Core."""
- __spddir = os.path.expanduser('~/.spd/')
- __version = None
- __client = None
- __core = None
-
- def __init__(self,clientmode=False): # {{{
- """init procedure"""
-
- initcheck = self.__startupCheck()
-
- self.__version = initcheck['version']
-
- if not clientmode:
- clientmode = initcheck['clientmode']
-
- try:
- __tempclient = __import__('spd' + clientmode)
- except ImportError:
- self.__ErrorHandler('__init__', 'clientmode ' + clientmode + ' not available!')
- else:
- self.__client = __tempclient.Cli()
- del __tempclient
-
- if 'passwordfield' in initcheck:
- self.__client._passwordfield = initcheck['passwordfield']
-
- del initcheck
-
- self.__core = spdCore.Core(ConfigSection='Main')
- # }}}
-
- def __ErrorHandler(self,function,message): # {{{
- """ErrorHandler of the Interface Module.
- # message: means the \'Exception\' to throw"""
- print "################################################"
- print "spdInterface ErrorHandler."
- print "ERRORFUNCTION: " + function
- print "ERRORMESSAGE: " + message
- print "################################################"
- exit(2)
- # }}}
-
- def __startupCheck(self): # {{{
- """Do initial checks"""
- __initargs = {}
-
- if not os.access(self.__spddir, os.F_OK):
- try:
- os.mkdir(self.__spddir)
- except Exception, e:
- self.__ErrorHandler('__startupCheck','Could not create ' + self.__spddir + ' Exception: ' + str(e))
-
- __config = spdConfig.Config()
-
- reval, __initargs['version'] = __config.getConfigVersion(raw=True)
-
- if reval > 0 and reval < 64:
- spdDefaults.createDefaultConfig(__config)
- 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')
- __initargs.update({ 'version' : __config.getConfigVersion() })
-
- reval, __initargs['clientmode'] = __config.getClientmode(raw=True)
-
- if reval > 0:
- print 'Clientmode not found...setting it to CLI\n'
- __input = raw_input('Press any key')
- __config.setClientmode('CLI')
- __initargs.update({ 'clientmode' : __config.getClientmode() })
-
- reval, __passwordfield = __config.getPasswordfield(raw=True)
-
- if reval == 0:
- __initargs.update({ 'passwordfield' : __passwordfield })
-
- return(__initargs)
- # }}}
-
- def __findPasswords(self,args): # {{{
- """Find the passwords by searchlist/searchstring handed.
- print the results in CLIENTMODE.
- # searchlist: optional string or list of keywords to search for."""
-
- if 'byid' in args:
- byid = args['byid']
-
- if 'args' in args:
- searchString = args['args']
- else:
- searchString = '%'
-
- if type(searchString).__name__ == 'list':
- searchlist = searchString
- else:
- searchlist = string.split(searchString)
-
- if len(searchlist) == 0:
- searchlist = ['%',]
-
- passdict = self.__core.searchEntry(searchlist,byid)
-
- return passdict
- # }}}
-
- def printPasswords(self,args): # {{{
- passdict = self.__findPasswords(args)
- self.__client.printPasswords(passdict, args)
- # }}}
-
- def deleteEntry(self, args): # {{{
- __passdict = self.__findPasswords(args)
-
- if len(__passdict) == 0:
- self.__ErrorHandler('deleteEntry','No matches found')
-
- self.__client.printPasswords(__passdict)
- ids = self.__client.deleteEntry(__passdict)
- self.__core.delEntry(ids)
- # }}}
-
- def editEntry(self,args): # {{{
- __passdict = self.__findPasswords(args)
- if len(__passdict) > 0:
- __newpassdict = self.__client.editEntry(__passdict)
- self.__core.editEntry(__newpassdict)
- else:
- self.__ErrorHandler('editEntry','no matches for ' + str(args["args"]) + 'found')
- # }}}
-
- def deleteColumn(self,args): # {{{
- if 'args' in args:
- columns = args['args']
- else:
- columns = []
- for column in columns:
- if column in self.__core.getColumns(showid=False):
- self.__core.delColumn(column)
- else:
- self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
- # }}}
-
- def addColumn(self,args): # {{{
- if 'args' in args:
- columns = args['args']
- else:
- columns = []
-
- for column in columns:
- self.__core.addColumn(column)
- # }}}
-
- def addEntry(self, args): # {{{
- Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
- self.__core.addEntry(Entry)
- # }}}
-
- def main(self): # {{{
- function, args = self.__client.parseArgs(self.__version)
- getattr(self, function)(args)
- # }}}
-
-# }}}
-
-
-# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
Copied: branches/spd-ng/src/Interfaces/cli.py (from rev 336, branches/spd-ng/src/spdCLI.py)
===================================================================
--- branches/spd-ng/src/Interfaces/cli.py (rev 0)
+++ branches/spd-ng/src/Interfaces/cli.py 2011-06-28 20:24:22 UTC (rev 337)
@@ -0,0 +1,265 @@
+"""Client Interfaces Module
+
+This is the Cli Module.
+Resistance is futile"""
+
+
+from optparse import OptionParser, OptionGroup
+from sys import stdout
+from re import sub, search
+
+__version__ = '0.3-alpha'
+_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)
+# }}}
+
+def printPasswords(passdict,args=None): # {{{
+ """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 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 })
+
+ 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')
+
+ __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"
+# }}}
+
+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
+# }}}
+
+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
+# }}}
+
+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
+# }}}
+
+def parseArgs(version): # {{{
+ __optionsdict = {}
+
+ parser = OptionParser( "%prog [Options] [Keywords]",
+ description = "SPD - Simple Password Displayer - CLI",
+ version = """spdCore """ + version +
+ """\nspdCLI """ + __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( "-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")
+
+ group.add_option( "--id",
+ action="store_true",
+ dest ="byid",
+ default=False,
+ help ="Handle Input given as ID(s)")
+
+ parser.add_option_group(group)
+
+ 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( "-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")
+
+ 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( "--delete-columns",
+ action = "store_true",
+ dest ="deleteColumn",
+ default = False,
+ help ="Delete Columns given")
+
+ parser.add_option_group(group)
+
+ (options, args) = parser.parse_args()
+
+ if options.widemode:
+ __outmode = 'wide'
+ else:
+ __outmode = 'line'
+
+ __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]
+
+ elif options.deleteColumn:
+ return ["deleteColumn", __optionsdict]
+ elif options.addColumn:
+ return ["addColumn", __optionsdict]
+
+ return ["printPasswords", __optionsdict]
+# }}}
+
+# EOF
+# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
Deleted: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-06-27 20:31:22 UTC (rev 336)
+++ branches/spd-ng/src/spdCLI.py 2011-06-28 20:24:22 UTC (rev 337)
@@ -1,261 +0,0 @@
-#!/usr/bin/python
-
-from optparse import OptionParser, OptionGroup
-from sys import stdout
-from re import sub, search
-
-__version__ = '0.3-alpha'
-
-
-class Cli(object): # {{{
- """This is the Cli Module.
- Resistance is futile"""
- __outmode = None
- __version__ = '0.3-alpha'
- _passwordfield = 'Password'
-
- def __ErrorHandler(self,function,message): # {{{
- """ErrorHandler of the Client Module.
- # function: the function which throws the error
- # message: means the \'Exception\' to throw"""
- print "################################################"
- print "spdCli ErrorHandler."
- print "ERRORFUNCTION: " + function
- print "ERRORMESSAGE: " + message
- print "################################################"
- exit(2)
- # }}}
-
- def printPasswords(self,passdict,args=None): # {{{
- """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 type(passdict).__name__ != 'NoneType' and len(passdict) != 0:
- if pwonly:
- if len(passdict['__ID']) > 1:
- self.__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
- else:
- print passdict[self._passwordfield][0]
-
- elif self.__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 self.__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))
-
- for key in passdict:
- stdout.write(key.ljust(__keylength[key]) + '|')
- stdout.write('\n')
-
- __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:
- self.__ErrorHandler('printPasswords', 'output mode unknown')
- else:
- print "No Results found"
- # }}}
-
- def editEntry(self,__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(self,__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
- # }}}
-
- def createEntry(self,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
- # }}}
-
- def parseArgs(self,version): # {{{
- parser = OptionParser( "%prog [Options] [Keywords]",
- description = "SPD - Simple Password Displayer - CLI",
- version = """spdCore """ + version +
- """\nspdCLI """ + self.__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( "-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")
-
- group.add_option( "--id",
- action="store_true",
- dest ="byid",
- default=False,
- help ="Handle Input given as ID(s)")
-
- parser.add_option_group(group)
-
- 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( "-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")
-
- 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( "--delete-columns",
- action = "store_true",
- dest ="deleteColumn",
- default = False,
- help ="Delete Columns given")
-
- parser.add_option_group(group)
-
- (options, args) = parser.parse_args()
-
- if options.widemode:
- self.__outmode = 'wide'
- else:
- self.__outmode = 'line'
-
- if options.addEntry:
- return ["addEntry", { 'args' : args }]
- elif options.deleteEntry:
- return ["deleteEntry", { 'byid' : options.byid, 'args' : args }]
- elif options.editEntry:
- return ["editEntry", { 'byid' : options.byid, 'args' : args }]
-
- elif options.deleteColumn:
- return ["deleteColumn", { 'args' : args }]
- elif options.addColumn:
- return ["addColumn", { 'args' : args }]
-
- return ["printPasswords", { 'byid' : options.byid, 'pwonly' : options.pwonly, 'args' : args }]
- # }}}
-
-# }}}
-
-# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2011-06-27 20:31:22 UTC (rev 336)
+++ branches/spd-ng/src/spdCore.py 2011-06-28 20:24:22 UTC (rev 337)
@@ -191,4 +191,4 @@
# }}}
# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
+# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
Copied: branches/spd-ng/src/spdInterface.py (from rev 336, branches/spd-ng/src/spdInterface/__init__.py)
===================================================================
--- branches/spd-ng/src/spdInterface.py (rev 0)
+++ branches/spd-ng/src/spdInterface.py 2011-06-28 20:24:22 UTC (rev 337)
@@ -0,0 +1,201 @@
+'''spdInterface Module.
+
+The Modules handles all the exchange between user and spdCore.
+Usage:
+ import spdInterface
+ Interface = spdInterface.Interface()
+ Interface.main()
+
+or force a clientmode with:
+ Interface = spdInterface.Interface('CLI')
+
+if building your own interface, name it spd"whatever" and pass "whatever"
+to the Interface Class. The Module must be in pythons include path.'''
+
+from sys import exit
+import os
+import string
+
+try:
+ import spdConfig
+ import spdDefaults
+ import spdCore
+except ImportError:
+ print '##### ERROR #####'
+ print 'spdInterface: spd not installed. Missing Modules.'
+ exit(2)
+
+__version__ = '0.3-alpha'
+
+class Interface(object): # {{{
+ """The Interface Module.
+ Interface between client and Core."""
+ __spddir = os.path.expanduser('~/.spd/')
+ __version = None
+ __client = None
+ __core = None
+
+ def __init__(self,clientmode=False): # {{{
+ """init procedure"""
+
+ initcheck = self.__startupCheck()
+
+ self.__version = initcheck['version']
+
+ if not clientmode:
+ clientmode = initcheck['clientmode']
+
+ try:
+ __tempclient = __import__('Interfaces.' + clientmode.lower())
+ except ImportError:
+ self.__ErrorHandler('__init__', 'clientmode ' + clientmode + ' not available!')
+ else:
+ self.__client = __tempclient.cli
+ del __tempclient
+
+ if 'passwordfield' in initcheck:
+ self.__client._passwordfield = initcheck['passwordfield']
+
+ del initcheck
+
+ self.__core = spdCore.Core(ConfigSection='Main')
+ # }}}
+
+ def __ErrorHandler(self,function,message): # {{{
+ """ErrorHandler of the Interface Module.
+ # message: means the \'Exception\' to throw"""
+ print "################################################"
+ print "spdInterface ErrorHandler."
+ print "ERRORFUNCTION: " + function
+ print "ERRORMESSAGE: " + message
+ print "################################################"
+ exit(2)
+ # }}}
+
+ def __startupCheck(self): # {{{
+ """Do initial checks"""
+ __initargs = {}
+
+ if not os.access(self.__spddir, os.F_OK):
+ try:
+ os.mkdir(self.__spddir)
+ except Exception, e:
+ self.__ErrorHandler('__startupCheck','Could not create ' + self.__spddir + ' Exception: ' + str(e))
+
+ __config = spdConfig.Config()
+
+ reval, __initargs['version'] = __config.getConfigVersion(raw=True)
+
+ if reval > 0 and reval < 64:
+ spdDefaults.createDefaultConfig(__config)
+ 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')
+ __initargs.update({ 'version' : __config.getConfigVersion() })
+
+ reval, __initargs['clientmode'] = __config.getClientmode(raw=True)
+
+ if reval > 0:
+ print 'Clientmode not found...setting it to CLI\n'
+ __input = raw_input('Press any key')
+ __config.setClientmode('CLI')
+ __initargs.update({ 'clientmode' : __config.getClientmode() })
+
+ reval, __passwordfield = __config.getPasswordfield(raw=True)
+
+ if reval == 0:
+ __initargs.update({ 'passwordfield' : __passwordfield })
+
+ return(__initargs)
+ # }}}
+
+ def __findPasswords(self,args): # {{{
+ """Find the passwords by searchlist/searchstring handed.
+ print the results in CLIENTMODE.
+ # searchlist: optional string or list of keywords to search for."""
+
+ if 'byid' in args:
+ byid = args['byid']
+
+ if 'args' in args:
+ searchString = args['args']
+ else:
+ searchString = '%'
+
+ if type(searchString).__name__ == 'list':
+ searchlist = searchString
+ else:
+ searchlist = string.split(searchString)
+
+ if len(searchlist) == 0:
+ searchlist = ['%',]
+
+ passdict = self.__core.searchEntry(searchlist,byid)
+
+ return passdict
+ # }}}
+
+ def printPasswords(self,args): # {{{
+ passdict = self.__findPasswords(args)
+ self.__client.printPasswords(passdict, args)
+ # }}}
+
+ def deleteEntry(self, args): # {{{
+ __passdict = self.__findPasswords(args)
+
+ if len(__passdict) == 0:
+ self.__ErrorHandler('deleteEntry','No matches found')
+
+ self.__client.printPasswords(__passdict)
+ ids = self.__client.deleteEntry(__passdict)
+ self.__core.delEntry(ids)
+ # }}}
+
+ def editEntry(self,args): # {{{
+ __passdict = self.__findPasswords(args)
+ if len(__passdict) > 0:
+ __newpassdict = self.__client.editEntry(__passdict)
+ self.__core.editEntry(__newpassdict)
+ else:
+ self.__ErrorHandler('editEntry','no matches for ' + str(args["args"]) + 'found')
+ # }}}
+
+ def deleteColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+ for column in columns:
+ if column in self.__core.getColumns(showid=False):
+ self.__core.delColumn(column)
+ else:
+ self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
+ # }}}
+
+ def addColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+
+ for column in columns:
+ self.__core.addColumn(column)
+ # }}}
+
+ def addEntry(self, args): # {{{
+ Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
+ self.__core.addEntry(Entry)
+ # }}}
+
+ def main(self): # {{{
+ function, args = self.__client.parseArgs(self.__version)
+ getattr(self, function)(args)
+ # }}}
+
+# }}}
+
+
+# EOF
+# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
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.
|
|
From: <Z3...@us...> - 2011-06-27 20:31:29
|
Revision: 336
http://spd.svn.sourceforge.net/spd/?rev=336&view=rev
Author: Z3po
Date: 2011-06-27 20:31:22 +0000 (Mon, 27 Jun 2011)
Log Message:
-----------
beginning to restructure the whole spd stuff
Modified Paths:
--------------
branches/spd-ng/src/spd
branches/spd-ng/src/spdCore.py
Added Paths:
-----------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdInterface/
branches/spd-ng/src/spdInterface/__init__.py
branches/spd-ng/src/spdStore/
branches/spd-ng/src/spdStore/__init__.py
Removed Paths:
-------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/spdStore.py
Modified: branches/spd-ng/src/spd
===================================================================
--- branches/spd-ng/src/spd 2011-04-14 19:51:29 UTC (rev 335)
+++ branches/spd-ng/src/spd 2011-06-27 20:31:22 UTC (rev 336)
@@ -2,5 +2,6 @@
import spdInterface
+
Interface = spdInterface.Interface()
Interface.main()
Deleted: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-04-14 19:51:29 UTC (rev 335)
+++ branches/spd-ng/src/spdCLI.py 2011-06-27 20:31:22 UTC (rev 336)
@@ -1,261 +0,0 @@
-#!/usr/bin/python
-
-from optparse import OptionParser, OptionGroup
-from sys import stdout
-from re import sub, search
-
-__version__ = '0.3-alpha'
-
-
-class Cli(object): # {{{
- """This is the Cli Module.
- Resistance is futile"""
- __outmode = None
- __version__ = '0.3-alpha'
- _passwordfield = 'Password'
-
- def __ErrorHandler(self,function,message): # {{{
- """ErrorHandler of the Client Module.
- # function: the function which throws the error
- # message: means the \'Exception\' to throw"""
- print "################################################"
- print "spdCli ErrorHandler."
- print "ERRORFUNCTION: " + function
- print "ERRORMESSAGE: " + message
- print "################################################"
- exit(2)
- # }}}
-
- def printPasswords(self,passdict,args=None): # {{{
- """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 type(passdict).__name__ != 'NoneType' and len(passdict) != 0:
- if pwonly:
- if len(passdict['__ID']) > 1:
- self.__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
- else:
- print passdict[self._passwordfield][0]
-
- elif self.__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 self.__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))
-
- for key in passdict:
- stdout.write(key.ljust(__keylength[key]) + '|')
- stdout.write('\n')
-
- __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:
- self.__ErrorHandler('printPasswords', 'output mode unknown')
- else:
- print "No Results found"
- # }}}
-
- def editEntry(self,__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(self,__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
- # }}}
-
- def createEntry(self,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
- # }}}
-
- def parseArgs(self,version): # {{{
- parser = OptionParser( "%prog [Options] [Keywords]",
- description = "SPD - Simple Password Displayer - CLI",
- version = """spdCore """ + version +
- """\nspdCLI """ + self.__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( "-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")
-
- group.add_option( "--id",
- action="store_true",
- dest ="byid",
- default=False,
- help ="Handle Input given as ID(s)")
-
- parser.add_option_group(group)
-
- 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( "-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")
-
- 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( "--delete-columns",
- action = "store_true",
- dest ="deleteColumn",
- default = False,
- help ="Delete Columns given")
-
- parser.add_option_group(group)
-
- (options, args) = parser.parse_args()
-
- if options.widemode:
- self.__outmode = 'wide'
- else:
- self.__outmode = 'line'
-
- if options.addEntry:
- return ["addEntry", { 'args' : args }]
- elif options.deleteEntry:
- return ["deleteEntry", { 'byid' : options.byid, 'args' : args }]
- elif options.editEntry:
- return ["editEntry", { 'byid' : options.byid, 'args' : args }]
-
- elif options.deleteColumn:
- return ["deleteColumn", { 'args' : args }]
- elif options.addColumn:
- return ["addColumn", { 'args' : args }]
-
- return ["printPasswords", { 'byid' : options.byid, 'pwonly' : options.pwonly, 'args' : args }]
- # }}}
-
-# }}}
-
-# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
Added: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py (rev 0)
+++ branches/spd-ng/src/spdCLI.py 2011-06-27 20:31:22 UTC (rev 336)
@@ -0,0 +1,261 @@
+#!/usr/bin/python
+
+from optparse import OptionParser, OptionGroup
+from sys import stdout
+from re import sub, search
+
+__version__ = '0.3-alpha'
+
+
+class Cli(object): # {{{
+ """This is the Cli Module.
+ Resistance is futile"""
+ __outmode = None
+ __version__ = '0.3-alpha'
+ _passwordfield = 'Password'
+
+ def __ErrorHandler(self,function,message): # {{{
+ """ErrorHandler of the Client Module.
+ # function: the function which throws the error
+ # message: means the \'Exception\' to throw"""
+ print "################################################"
+ print "spdCli ErrorHandler."
+ print "ERRORFUNCTION: " + function
+ print "ERRORMESSAGE: " + message
+ print "################################################"
+ exit(2)
+ # }}}
+
+ def printPasswords(self,passdict,args=None): # {{{
+ """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 type(passdict).__name__ != 'NoneType' and len(passdict) != 0:
+ if pwonly:
+ if len(passdict['__ID']) > 1:
+ self.__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
+ else:
+ print passdict[self._passwordfield][0]
+
+ elif self.__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 self.__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))
+
+ for key in passdict:
+ stdout.write(key.ljust(__keylength[key]) + '|')
+ stdout.write('\n')
+
+ __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:
+ self.__ErrorHandler('printPasswords', 'output mode unknown')
+ else:
+ print "No Results found"
+ # }}}
+
+ def editEntry(self,__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(self,__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
+ # }}}
+
+ def createEntry(self,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
+ # }}}
+
+ def parseArgs(self,version): # {{{
+ parser = OptionParser( "%prog [Options] [Keywords]",
+ description = "SPD - Simple Password Displayer - CLI",
+ version = """spdCore """ + version +
+ """\nspdCLI """ + self.__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( "-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")
+
+ group.add_option( "--id",
+ action="store_true",
+ dest ="byid",
+ default=False,
+ help ="Handle Input given as ID(s)")
+
+ parser.add_option_group(group)
+
+ 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( "-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")
+
+ 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( "--delete-columns",
+ action = "store_true",
+ dest ="deleteColumn",
+ default = False,
+ help ="Delete Columns given")
+
+ parser.add_option_group(group)
+
+ (options, args) = parser.parse_args()
+
+ if options.widemode:
+ self.__outmode = 'wide'
+ else:
+ self.__outmode = 'line'
+
+ if options.addEntry:
+ return ["addEntry", { 'args' : args }]
+ elif options.deleteEntry:
+ return ["deleteEntry", { 'byid' : options.byid, 'args' : args }]
+ elif options.editEntry:
+ return ["editEntry", { 'byid' : options.byid, 'args' : args }]
+
+ elif options.deleteColumn:
+ return ["deleteColumn", { 'args' : args }]
+ elif options.addColumn:
+ return ["addColumn", { 'args' : args }]
+
+ return ["printPasswords", { 'byid' : options.byid, 'pwonly' : options.pwonly, 'args' : args }]
+ # }}}
+
+# }}}
+
+# EOF
+# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2011-04-14 19:51:29 UTC (rev 335)
+++ branches/spd-ng/src/spdCore.py 2011-06-27 20:31:22 UTC (rev 336)
@@ -7,7 +7,10 @@
import sqlite3
import re
+import random
+import string
#import spdConfig
+import spdStore
__version__ = '0.3-alpha'
@@ -172,6 +175,20 @@
""")
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:shiftwidth=3
Copied: branches/spd-ng/src/spdInterface/__init__.py (from rev 335, branches/spd-ng/src/spdInterface.py)
===================================================================
--- branches/spd-ng/src/spdInterface/__init__.py (rev 0)
+++ branches/spd-ng/src/spdInterface/__init__.py 2011-06-27 20:31:22 UTC (rev 336)
@@ -0,0 +1,201 @@
+'''spdInterface Module.
+
+The Modules handles all the exchange between user and spdCore.
+Usage:
+ import spdInterface
+ Interface = spdInterface.Interface()
+ Interface.main()
+
+or force a clientmode with:
+ Interface = spdInterface.Interface('CLI')
+
+if building your own interface, name it spd"whatever" and pass "whatever"
+to the Interface Class. The Module must be in pythons include path.'''
+
+from sys import exit
+import os
+import string
+
+try:
+ import spdConfig
+ import spdDefaults
+ import spdCore
+except ImportError:
+ print '##### ERROR #####'
+ print 'spdInterface: spd not installed. Missing Modules.'
+ exit(2)
+
+__version__ = '0.3-alpha'
+
+class Interface(object): # {{{
+ """The Interface Module.
+ Interface between client and Core."""
+ __spddir = os.path.expanduser('~/.spd/')
+ __version = None
+ __client = None
+ __core = None
+
+ def __init__(self,clientmode=False): # {{{
+ """init procedure"""
+
+ initcheck = self.__startupCheck()
+
+ self.__version = initcheck['version']
+
+ if not clientmode:
+ clientmode = initcheck['clientmode']
+
+ try:
+ __tempclient = __import__('spd' + clientmode)
+ except ImportError:
+ self.__ErrorHandler('__init__', 'clientmode ' + clientmode + ' not available!')
+ else:
+ self.__client = __tempclient.Cli()
+ del __tempclient
+
+ if 'passwordfield' in initcheck:
+ self.__client._passwordfield = initcheck['passwordfield']
+
+ del initcheck
+
+ self.__core = spdCore.Core(ConfigSection='Main')
+ # }}}
+
+ def __ErrorHandler(self,function,message): # {{{
+ """ErrorHandler of the Interface Module.
+ # message: means the \'Exception\' to throw"""
+ print "################################################"
+ print "spdInterface ErrorHandler."
+ print "ERRORFUNCTION: " + function
+ print "ERRORMESSAGE: " + message
+ print "################################################"
+ exit(2)
+ # }}}
+
+ def __startupCheck(self): # {{{
+ """Do initial checks"""
+ __initargs = {}
+
+ if not os.access(self.__spddir, os.F_OK):
+ try:
+ os.mkdir(self.__spddir)
+ except Exception, e:
+ self.__ErrorHandler('__startupCheck','Could not create ' + self.__spddir + ' Exception: ' + str(e))
+
+ __config = spdConfig.Config()
+
+ reval, __initargs['version'] = __config.getConfigVersion(raw=True)
+
+ if reval > 0 and reval < 64:
+ spdDefaults.createDefaultConfig(__config)
+ 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')
+ __initargs.update({ 'version' : __config.getConfigVersion() })
+
+ reval, __initargs['clientmode'] = __config.getClientmode(raw=True)
+
+ if reval > 0:
+ print 'Clientmode not found...setting it to CLI\n'
+ __input = raw_input('Press any key')
+ __config.setClientmode('CLI')
+ __initargs.update({ 'clientmode' : __config.getClientmode() })
+
+ reval, __passwordfield = __config.getPasswordfield(raw=True)
+
+ if reval == 0:
+ __initargs.update({ 'passwordfield' : __passwordfield })
+
+ return(__initargs)
+ # }}}
+
+ def __findPasswords(self,args): # {{{
+ """Find the passwords by searchlist/searchstring handed.
+ print the results in CLIENTMODE.
+ # searchlist: optional string or list of keywords to search for."""
+
+ if 'byid' in args:
+ byid = args['byid']
+
+ if 'args' in args:
+ searchString = args['args']
+ else:
+ searchString = '%'
+
+ if type(searchString).__name__ == 'list':
+ searchlist = searchString
+ else:
+ searchlist = string.split(searchString)
+
+ if len(searchlist) == 0:
+ searchlist = ['%',]
+
+ passdict = self.__core.searchEntry(searchlist,byid)
+
+ return passdict
+ # }}}
+
+ def printPasswords(self,args): # {{{
+ passdict = self.__findPasswords(args)
+ self.__client.printPasswords(passdict, args)
+ # }}}
+
+ def deleteEntry(self, args): # {{{
+ __passdict = self.__findPasswords(args)
+
+ if len(__passdict) == 0:
+ self.__ErrorHandler('deleteEntry','No matches found')
+
+ self.__client.printPasswords(__passdict)
+ ids = self.__client.deleteEntry(__passdict)
+ self.__core.delEntry(ids)
+ # }}}
+
+ def editEntry(self,args): # {{{
+ __passdict = self.__findPasswords(args)
+ if len(__passdict) > 0:
+ __newpassdict = self.__client.editEntry(__passdict)
+ self.__core.editEntry(__newpassdict)
+ else:
+ self.__ErrorHandler('editEntry','no matches for ' + str(args["args"]) + 'found')
+ # }}}
+
+ def deleteColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+ for column in columns:
+ if column in self.__core.getColumns(showid=False):
+ self.__core.delColumn(column)
+ else:
+ self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
+ # }}}
+
+ def addColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+
+ for column in columns:
+ self.__core.addColumn(column)
+ # }}}
+
+ def addEntry(self, args): # {{{
+ Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
+ self.__core.addEntry(Entry)
+ # }}}
+
+ def main(self): # {{{
+ function, args = self.__client.parseArgs(self.__version)
+ getattr(self, function)(args)
+ # }}}
+
+# }}}
+
+
+# EOF
+# vim:foldmethod=marker:tabstop=3:autoindent:noexpandtab:shiftwidth=3
Deleted: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2011-04-14 19:51:29 UTC (rev 335)
+++ branches/spd-ng/src/spdInterface.py 2011-06-27 20:31:22 UTC (rev 336)
@@ -1,199 +0,0 @@
-'''spdInterface Module.
-
-The Modules handles all the exchange between user and spdCore.
-Usage:
- import spdInterface
- Interface = spdInterface.Interface()
- Interface.main()
-
-or force a clientmode with:
- Interface = spdInterface.Interface('CLI')
-
-if building your own interface, name it spd"whatever" and pass "whatever"
-to the Interface Class. The Module must be in pythons include path.'''
-
-from sys import exit
-import os
-import string
-try:
- import spdConfig
- import spdDefaults
- import spdCore
-except ImportError:
- print 'spd not installed. Missing Modules.'
- exit(2)
-
-__version__ = '0.3-alpha'
-
-class Interface(object): # {{{
- """The Interface Module.
- Interface between client and Core."""
- __spddir = os.path.expanduser('~/.spd/')
- __version = None
- __client = None
- __core = None
-
- def __init__(self,clientmode=False): # {{{
- """init procedure"""
-
- initcheck = self.__startupCheck()
-
- self.__version = initcheck['version']
-
- if not clientmode:
- clientmode = initcheck['clientmode']
-
- try:
- __tempclient = __import__('spd' + clientmode)
- except ImportError:
- self.__ErrorHandler('__init__', 'clientmode ' + clientmode + ' not available!')
- else:
- self.__client = __tempclient.Cli()
- del __tempclient
-
- if 'passwordfield' in initcheck:
- self.__client._passwordfield = initcheck['passwordfield']
-
- del initcheck
-
- self.__core = spdCore.Core(ConfigSection='Main')
- # }}}
-
- def __ErrorHandler(self,function,message): # {{{
- """ErrorHandler of the Interface Module.
- # message: means the \'Exception\' to throw"""
- print "################################################"
- print "spdInterface ErrorHandler."
- print "ERRORFUNCTION: " + function
- print "ERRORMESSAGE: " + message
- print "################################################"
- exit(2)
- # }}}
-
- def __startupCheck(self): # {{{
- """Do initial checks"""
- __initargs = {}
-
- if not os.access(self.__spddir, os.F_OK):
- try:
- os.mkdir(self.__spddir)
- except Exception, e:
- self.__ErrorHandler('__startupCheck','Could not create ' + self.__spddir + ' Exception: ' + str(e))
-
- __config = spdConfig.Config()
-
- reval, __initargs['version'] = __config.getConfigVersion(raw=True)
-
- if reval > 0 and reval < 64:
- spdDefaults.createDefaultConfig(__config)
- 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')
- __initargs.update({ 'version' : __config.getConfigVersion() })
-
- reval, __initargs['clientmode'] = __config.getClientmode(raw=True)
-
- if reval > 0:
- print 'Clientmode not found...setting it to CLI\n'
- __input = raw_input('Press any key')
- __config.setClientmode('CLI')
- __initargs.update({ 'clientmode' : __config.getClientmode() })
-
- reval, __passwordfield = __config.getPasswordfield(raw=True)
-
- if reval == 0:
- __initargs.update({ 'passwordfield' : __passwordfield })
-
- return(__initargs)
- # }}}
-
- def __findPasswords(self,args): # {{{
- """Find the passwords by searchlist/searchstring handed.
- print the results in CLIENTMODE.
- # searchlist: optional string or list of keywords to search for."""
-
- if 'byid' in args:
- byid = args['byid']
-
- if 'args' in args:
- searchString = args['args']
- else:
- searchString = '%'
-
- if type(searchString).__name__ == 'list':
- searchlist = searchString
- else:
- searchlist = string.split(searchString)
-
- if len(searchlist) == 0:
- searchlist = ['%',]
-
- passdict = self.__core.searchEntry(searchlist,byid)
-
- return passdict
- # }}}
-
- def printPasswords(self,args): # {{{
- passdict = self.__findPasswords(args)
- self.__client.printPasswords(passdict, args)
- # }}}
-
- def deleteEntry(self, args): # {{{
- __passdict = self.__findPasswords(args)
-
- if len(__passdict) == 0:
- self.__ErrorHandler('deleteEntry','No matches found')
-
- self.__client.printPasswords(__passdict)
- ids = self.__client.deleteEntry(__passdict)
- self.__core.delEntry(ids)
- # }}}
-
- def editEntry(self,args): # {{{
- __passdict = self.__findPasswords(args)
- if len(__passdict) > 0:
- __newpassdict = self.__client.editEntry(__passdict)
- self.__core.editEntry(__newpassdict)
- else:
- self.__ErrorHandler('editEntry','no matches for ' + str(args["args"]) + 'found')
- # }}}
-
- def deleteColumn(self,args): # {{{
- if 'args' in args:
- columns = args['args']
- else:
- columns = []
- for column in columns:
- if column in self.__core.getColumns(showid=False):
- self.__core.delColumn(column)
- else:
- self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
- # }}}
-
- def addColumn(self,args): # {{{
- if 'args' in args:
- columns = args['args']
- else:
- columns = []
-
- for column in columns:
- self.__core.addColumn(column)
- # }}}
-
- def addEntry(self, args): # {{{
- Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
- self.__core.addEntry(Entry)
- # }}}
-
- def main(self): # {{{
- function, args = self.__client.parseArgs(self.__version)
- getattr(self, function)(args)
- # }}}
-
-# }}}
-
-
-# EOF
-# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
Added: branches/spd-ng/src/spdStore/__init__.py
===================================================================
--- branches/spd-ng/src/spdStore/__init__.py (rev 0)
+++ branches/spd-ng/src/spdStore/__init__.py 2011-06-27 20:31:22 UTC (rev 336)
@@ -0,0 +1,10 @@
+'''spdStore Module
+
+This Module takes Care of the storage Engine used by SPD.
+Currently Implemented Storage Types are
+- plain
+- gpg
+Call the Store() Class with supplying the used storage type'''
+
+# EOF
+# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
Deleted: branches/spd-ng/src/spdStore.py
===================================================================
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-04-14 19:51:36
|
Revision: 335
http://spd.svn.sourceforge.net/spd/?rev=335&view=rev
Author: Z3po
Date: 2011-04-14 19:51:29 +0000 (Thu, 14 Apr 2011)
Log Message:
-----------
multiline support in add and edit entry function. start a multiline with """ and end with it too.
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-04-13 18:51:47 UTC (rev 334)
+++ branches/spd-ng/src/spdCLI.py 2011-04-14 19:51:29 UTC (rev 335)
@@ -111,7 +111,15 @@
if __passdict[__column][i] is None:
__passdict[__column][i] = ''
__input = raw_input(__column + ' (' + str(__passdict[__column][i]) + '): ')
- if __input != '':
+ 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
# }}}
@@ -134,6 +142,14 @@
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
# }}}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-04-13 18:51:53
|
Revision: 334
http://spd.svn.sourceforge.net/spd/?rev=334&view=rev
Author: Z3po
Date: 2011-04-13 18:51:47 +0000 (Wed, 13 Apr 2011)
Log Message:
-----------
minor fix of --wide output mode
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-02-04 16:16:47 UTC (rev 333)
+++ branches/spd-ng/src/spdCLI.py 2011-04-13 18:51:47 UTC (rev 334)
@@ -2,7 +2,7 @@
from optparse import OptionParser, OptionGroup
from sys import stdout
-from re import sub
+from re import sub, search
__version__ = '0.3-alpha'
@@ -67,8 +67,13 @@
__keylength[key] = len(key)
for value in passdict[key]:
if value is not None:
- if len(str(value)) > __keylength[key]:
- __keylength[key] = len(str(value))
+ 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]) + '|')
@@ -87,7 +92,7 @@
stdout.write('\n' + __space)
stdout.write(line.ljust(__keylength[key]) + '|')
__count += 1
- __space = __space + ''.ljust(__keylength[key]) + ' '
+ __space = __space + ''.ljust(__keylength[key],'>') + '>'
stdout.write('\n')
else:
self.__ErrorHandler('printPasswords', 'output mode unknown')
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.
|
|
From: <Z3...@us...> - 2011-02-04 16:16:54
|
Revision: 333
http://spd.svn.sourceforge.net/spd/?rev=333&view=rev
Author: Z3po
Date: 2011-02-04 16:16:47 +0000 (Fri, 04 Feb 2011)
Log Message:
-----------
Bugfixes for bugs caused by change of parameter transmission
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdDefaults.py
branches/spd-ng/src/spdInterface.py
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-01-17 22:35:35 UTC (rev 332)
+++ branches/spd-ng/src/spdCLI.py 2011-02-04 16:16:47 UTC (rev 333)
@@ -1,15 +1,18 @@
#!/usr/bin/python
from optparse import OptionParser, OptionGroup
-import sys
-import re
+from sys import stdout
+from re import sub
+__version__ = '0.3-alpha'
+
+
class Cli(object): # {{{
"""This is the Cli Module.
Resistance is futile"""
-
__outmode = None
- __version = '0.3-alpha'
+ __version__ = '0.3-alpha'
+ _passwordfield = 'Password'
def __ErrorHandler(self,function,message): # {{{
"""ErrorHandler of the Client Module.
@@ -38,7 +41,7 @@
if len(passdict['__ID']) > 1:
self.__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
else:
- print passdict['Password'][0] # FIXME!!
+ print passdict[self._passwordfield][0]
elif self.__outmode == 'line':
length = 0
@@ -52,7 +55,7 @@
if key == '__ID':
continue
if type(passdict[key][i]).__name__ != 'NoneType':
- print key.ljust(length) + ': ' + re.sub('\n','\n ' + ' '.ljust(length),passdict[key][i])
+ print key.ljust(length) + ': ' + sub('\n','\n ' + ' '.ljust(length),passdict[key][i])
else:
print key.ljust(length) + ': '
print ""
@@ -68,8 +71,8 @@
__keylength[key] = len(str(value))
for key in passdict:
- sys.stdout.write(key.ljust(__keylength[key]) + '|')
- sys.stdout.write('\n')
+ stdout.write(key.ljust(__keylength[key]) + '|')
+ stdout.write('\n')
__entries = len(passdict.values()[0])
@@ -81,11 +84,11 @@
__count = 0
for line in str(passdict[key][i]).split('\n'):
if __count > 0:
- sys.stdout.write('\n' + __space)
- sys.stdout.write(line.ljust(__keylength[key]) + '|')
+ stdout.write('\n' + __space)
+ stdout.write(line.ljust(__keylength[key]) + '|')
__count += 1
__space = __space + ''.ljust(__keylength[key]) + ' '
- sys.stdout.write('\n')
+ stdout.write('\n')
else:
self.__ErrorHandler('printPasswords', 'output mode unknown')
else:
@@ -134,7 +137,7 @@
parser = OptionParser( "%prog [Options] [Keywords]",
description = "SPD - Simple Password Displayer - CLI",
version = """spdCore """ + version +
- """\nspdCLI """ + self.__version,
+ """\nspdCLI """ + self.__version__,
epilog = """With no parameters it will print out everything!
Please report Bugs or Feature Request at http://spd.sourceforge.net""")
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2011-01-17 22:35:35 UTC (rev 332)
+++ branches/spd-ng/src/spdConfig.py 2011-02-04 16:16:47 UTC (rev 333)
@@ -2,8 +2,10 @@
from ConfigParser import RawConfigParser
import os
-import sys
+#import sys
+__version__ = '0.3-alpha'
+
class Config(object): # {{{
'''This is the Configuration Module
You can read or set config options'''
@@ -28,7 +30,7 @@
print "Configfile: " + self.__configfile
print "ERRORMESSAGE: " + message
print "################################################"
- sys.exit(2)
+ exit(2)
# }}}
def __checkConfigFileExist(self): # {{{
@@ -124,18 +126,6 @@
return 0
# }}}
- def __listSections(self): # {{{
- """Return all sections from configfile."""
-
- reval, config = self.__checkConfigFileReadable()
-
- if reval > 0:
- return reval, None
-
- return 0, config.sections()
-
- # }}}
-
def __delSection(self,section): # {{{
"""delete a Section from configfile.
# section: the section to delete."""
@@ -215,6 +205,21 @@
# }}}
+ def getSections(self, raw=False): # {{{
+ """Return all sections from configfile."""
+
+ reval, config = self.__checkConfigFileReadable()
+
+ if reval > 0:
+ self.__ErrorHandler(self.ReturnCodes[reval])
+
+ if raw:
+ return 0, config.sections()
+
+ return config.sections()
+
+ # }}}
+
def addConfigSection(self,section): # {{{
reval = self.__addSection(section)
@@ -284,6 +289,37 @@
self.__ErrorHandler(self.ReturnCodes[reval])
# }}}
+ def getPasswordfield(self, raw=False): # {{{
+ '''get the clientmode.
+ # return the Password Column'''
+
+ reval, clientmode = self.__getOption('Main', 'passwordfield')
+
+ 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 raw:
+ return reval, clientmode
+
+ return clientmode
+ # }}}
+
+ 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])
+ # }}}
+
# }}}
# EOF
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2011-01-17 22:35:35 UTC (rev 332)
+++ branches/spd-ng/src/spdCore.py 2011-02-04 16:16:47 UTC (rev 333)
@@ -7,7 +7,10 @@
import sqlite3
import re
+#import spdConfig
+__version__ = '0.3-alpha'
+
class Core(object):
# create the database from the stuff out of the store
Modified: branches/spd-ng/src/spdDefaults.py
===================================================================
--- branches/spd-ng/src/spdDefaults.py 2011-01-17 22:35:35 UTC (rev 332)
+++ branches/spd-ng/src/spdDefaults.py 2011-02-04 16:16:47 UTC (rev 333)
@@ -1,9 +1,11 @@
"""This is the Defaults Configuration Module
Trying to create the defaults"""
-import spdConfig
+#import spdConfig
import os
+__version__ = '0.3-alpha'
+
def __ErrorHandler(function, message): # {{{
'''ErrorHandler of the Defaults Module.
# function: the function who called the ErrorHandler
@@ -13,7 +15,7 @@
print 'ERRORFUNCTION: ' + function
print 'ERRORMESSAGE: ' + message
print '################################################'
- sys.exit(2)
+ exit(2)
# }}}
def __oldSPDCheck(): # {{{
@@ -43,6 +45,7 @@
config.addConfigSection('Main')
config.setConfigVersion('0.3-alpha')
config.setClientmode('CLI')
+ config.setPasswordfield('Password')
__input = raw_input('Done. Back to normal. [ENTER]')
# }}}
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2011-01-17 22:35:35 UTC (rev 332)
+++ branches/spd-ng/src/spdInterface.py 2011-02-04 16:16:47 UTC (rev 333)
@@ -23,6 +23,8 @@
print 'spd not installed. Missing Modules.'
exit(2)
+__version__ = '0.3-alpha'
+
class Interface(object): # {{{
"""The Interface Module.
Interface between client and Core."""
@@ -41,8 +43,6 @@
if not clientmode:
clientmode = initcheck['clientmode']
- del initcheck
-
try:
__tempclient = __import__('spd' + clientmode)
except ImportError:
@@ -51,6 +51,11 @@
self.__client = __tempclient.Cli()
del __tempclient
+ if 'passwordfield' in initcheck:
+ self.__client._passwordfield = initcheck['passwordfield']
+
+ del initcheck
+
self.__core = spdCore.Core(ConfigSection='Main')
# }}}
@@ -67,6 +72,7 @@
def __startupCheck(self): # {{{
"""Do initial checks"""
+ __initargs = {}
if not os.access(self.__spddir, os.F_OK):
try:
@@ -76,28 +82,31 @@
__config = spdConfig.Config()
- reval, __version = __config.getConfigVersion(raw=True)
+ reval, __initargs['version'] = __config.getConfigVersion(raw=True)
if reval > 0 and reval < 64:
spdDefaults.createDefaultConfig(__config)
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')
- __version = __config.getConfigVersion()
+ __initargs.update({ 'version' : __config.getConfigVersion() })
- reval, clientmode = __config.getClientmode(raw=True)
+ reval, __initargs['clientmode'] = __config.getClientmode(raw=True)
if reval > 0:
print 'Clientmode not found...setting it to CLI\n'
__input = raw_input('Press any key')
__config.setClientmode('CLI')
- clientmode = __config.getClientmode()
+ __initargs.update({ 'clientmode' : __config.getClientmode() })
- return({ 'version' : __version,
- 'clientmode' : clientmode })
+ reval, __passwordfield = __config.getPasswordfield(raw=True)
+
+ if reval == 0:
+ __initargs.update({ 'passwordfield' : __passwordfield })
+
+ return(__initargs)
# }}}
def __findPasswords(self,args): # {{{
@@ -148,7 +157,7 @@
__newpassdict = self.__client.editEntry(__passdict)
self.__core.editEntry(__newpassdict)
else:
- self.__ErrorHandler('editEntry','no matches for ' + str(args[1]) + 'found')
+ self.__ErrorHandler('editEntry','no matches for ' + str(args["args"]) + 'found')
# }}}
def deleteColumn(self,args): # {{{
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-01-17 22:35:41
|
Revision: 332
http://spd.svn.sourceforge.net/spd/?rev=332&view=rev
Author: Z3po
Date: 2011-01-17 22:35:35 +0000 (Mon, 17 Jan 2011)
Log Message:
-----------
improved argument handling
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdInterface.py
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-01-16 19:48:31 UTC (rev 331)
+++ branches/spd-ng/src/spdCLI.py 2011-01-17 22:35:35 UTC (rev 332)
@@ -23,11 +23,16 @@
exit(2)
# }}}
- def printPasswords(self,passdict,pwonly=False): # {{{
+ def printPasswords(self,passdict,args=None): # {{{
"""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 type(passdict).__name__ != 'NoneType' and len(passdict) != 0:
if pwonly:
if len(passdict['__ID']) > 1:
@@ -212,18 +217,18 @@
self.__outmode = 'line'
if options.addEntry:
- return ["addEntry", args]
+ return ["addEntry", { 'args' : args }]
elif options.deleteEntry:
- return ["deleteEntry", [ options.byid, args]]
+ return ["deleteEntry", { 'byid' : options.byid, 'args' : args }]
elif options.editEntry:
- return ["editEntry", [ options.byid, args]]
+ return ["editEntry", { 'byid' : options.byid, 'args' : args }]
elif options.deleteColumn:
- return ["deleteColumn", args]
+ return ["deleteColumn", { 'args' : args }]
elif options.addColumn:
- return ["addColumn", args]
+ return ["addColumn", { 'args' : args }]
- return ["printPasswords", [ options.byid, options.pwonly, args]]
+ return ["printPasswords", { 'byid' : options.byid, 'pwonly' : options.pwonly, 'args' : args }]
# }}}
# }}}
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2011-01-16 19:48:31 UTC (rev 331)
+++ branches/spd-ng/src/spdInterface.py 2011-01-17 22:35:35 UTC (rev 332)
@@ -105,7 +105,13 @@
print the results in CLIENTMODE.
# searchlist: optional string or list of keywords to search for."""
- byid, searchString = args
+ if 'byid' in args:
+ byid = args['byid']
+
+ if 'args' in args:
+ searchString = args['args']
+ else:
+ searchString = '%'
if type(searchString).__name__ == 'list':
searchlist = searchString
@@ -114,19 +120,18 @@
if len(searchlist) == 0:
searchlist = ['%',]
+
passdict = self.__core.searchEntry(searchlist,byid)
return passdict
# }}}
def printPasswords(self,args): # {{{
- byid, pwonly, keywords = args
- passdict = self.__findPasswords([ byid, keywords ])
- self.__client.printPasswords(passdict, pwonly)
+ passdict = self.__findPasswords(args)
+ self.__client.printPasswords(passdict, args)
# }}}
def deleteEntry(self, args): # {{{
- byid, searchString = args
__passdict = self.__findPasswords(args)
if len(__passdict) == 0:
@@ -146,7 +151,11 @@
self.__ErrorHandler('editEntry','no matches for ' + str(args[1]) + 'found')
# }}}
- def deleteColumn(self,columns): # {{{
+ def deleteColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
for column in columns:
if column in self.__core.getColumns(showid=False):
self.__core.delColumn(column)
@@ -154,7 +163,12 @@
self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
# }}}
- def addColumn(self,columns): # {{{
+ def addColumn(self,args): # {{{
+ if 'args' in args:
+ columns = args['args']
+ else:
+ columns = []
+
for column in columns:
self.__core.addColumn(column)
# }}}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-01-16 19:48:38
|
Revision: 331
http://spd.svn.sourceforge.net/spd/?rev=331&view=rev
Author: Z3po
Date: 2011-01-16 19:48:31 +0000 (Sun, 16 Jan 2011)
Log Message:
-----------
improved argument passing, added pwonly option
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdInterface.py
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2011-01-08 09:08:07 UTC (rev 330)
+++ branches/spd-ng/src/spdCLI.py 2011-01-16 19:48:31 UTC (rev 331)
@@ -23,13 +23,19 @@
exit(2)
# }}}
- def printPasswords(self,passdict): # {{{
+ def printPasswords(self,passdict,pwonly=False): # {{{
"""Print the passwords out of a dictionary.
# passdict: the dictionary full of passwords"""
__keylength = {}
if type(passdict).__name__ != 'NoneType' and len(passdict) != 0:
- if self.__outmode == 'line':
+ if pwonly:
+ if len(passdict['__ID']) > 1:
+ self.__ErrorHandler('printPasswords', 'pwonly selected but more than one result returned')
+ else:
+ print passdict['Password'][0] # FIXME!!
+
+ elif self.__outmode == 'line':
length = 0
for key in passdict.keys():
if length < len(key):
@@ -41,7 +47,7 @@
if key == '__ID':
continue
if type(passdict[key][i]).__name__ != 'NoneType':
- print key.ljust(length) + ': ' + passdict[key][i]
+ print key.ljust(length) + ': ' + re.sub('\n','\n ' + ' '.ljust(length),passdict[key][i])
else:
print key.ljust(length) + ': '
print ""
@@ -97,6 +103,19 @@
return __passdict
# }}}
+ def deleteEntry(self,__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
+ # }}}
+
def createEntry(self,columns): # {{{
Entry = {}
print "Adding a new Entry to our passfile"
@@ -149,20 +168,15 @@
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)")
+
parser.add_option_group(group)
-
- #parser.add_option( "--add-column",
- # metavar="Collumn",
- # dest = "addcolumn",
- # default=False,
- # help = "Add a Collumn to Passfile")
- #
- #parser.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( "-l", "--local",
# action="store_true",
@@ -192,24 +206,24 @@
(options, args) = parser.parse_args()
+ if options.widemode:
+ self.__outmode = 'wide'
+ else:
+ self.__outmode = 'line'
+
if options.addEntry:
return ["addEntry", args]
elif options.deleteEntry:
return ["deleteEntry", [ options.byid, args]]
elif options.editEntry:
- return ["editEntry", args]
+ return ["editEntry", [ options.byid, args]]
elif options.deleteColumn:
return ["deleteColumn", args]
elif options.addColumn:
return ["addColumn", args]
- elif options.widemode:
- self.__outmode = 'wide'
- else:
- self.__outmode = 'line'
-
- return ["printPasswords", args]
+ return ["printPasswords", [ options.byid, options.pwonly, args]]
# }}}
# }}}
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2011-01-08 09:08:07 UTC (rev 330)
+++ branches/spd-ng/src/spdInterface.py 2011-01-16 19:48:31 UTC (rev 331)
@@ -51,7 +51,7 @@
self.__client = __tempclient.Cli()
del __tempclient
- self.__core = spdCore.Core()
+ self.__core = spdCore.Core(ConfigSection='Main')
# }}}
def __ErrorHandler(self,function,message): # {{{
@@ -100,11 +100,13 @@
'clientmode' : clientmode })
# }}}
- def __findPasswords(self,searchString,byid=False): # {{{
+ def __findPasswords(self,args): # {{{
"""Find the passwords by searchlist/searchstring handed.
print the results in CLIENTMODE.
# searchlist: optional string or list of keywords to search for."""
+ byid, searchString = args
+
if type(searchString).__name__ == 'list':
searchlist = searchString
else:
@@ -117,32 +119,31 @@
return passdict
# }}}
- def printPasswords(self,searchString='%'): # {{{
- passdict = self.__findPasswords(searchString)
- self.__client.printPasswords(passdict)
+ def printPasswords(self,args): # {{{
+ byid, pwonly, keywords = args
+ passdict = self.__findPasswords([ byid, keywords ])
+ self.__client.printPasswords(passdict, pwonly)
# }}}
- def deleteEntry(self, values): # {{{
- byid, searchString = values
- __passdict = self.__findPasswords(searchString,byid)
+ def deleteEntry(self, args): # {{{
+ byid, searchString = args
+ __passdict = self.__findPasswords(args)
if len(__passdict) == 0:
self.__ErrorHandler('deleteEntry','No matches found')
- if len(__passdict['__ID']) > 1:
- print str(__passdict)
- else:
- print str(__passdict)
- self.__core.delEntry(__passdict['__ID'])
+ self.__client.printPasswords(__passdict)
+ ids = self.__client.deleteEntry(__passdict)
+ self.__core.delEntry(ids)
# }}}
- def editEntry(self,ids): # {{{
- __passdict = self.__findPasswords(ids,byid=True)
+ def editEntry(self,args): # {{{
+ __passdict = self.__findPasswords(args)
if len(__passdict) > 0:
__newpassdict = self.__client.editEntry(__passdict)
self.__core.editEntry(__newpassdict)
else:
- self.__ErrorHandler('editEntry','no matches for ' + str(ids) + 'found')
+ self.__ErrorHandler('editEntry','no matches for ' + str(args[1]) + 'found')
# }}}
def deleteColumn(self,columns): # {{{
@@ -164,8 +165,8 @@
# }}}
def main(self): # {{{
- function, value = self.__client.parseArgs(self.__version)
- getattr(self, function)(value)
+ function, args = self.__client.parseArgs(self.__version)
+ getattr(self, function)(args)
# }}}
# }}}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2011-01-08 09:08:14
|
Revision: 330
http://spd.svn.sourceforge.net/spd/?rev=330&view=rev
Author: Z3po
Date: 2011-01-08 09:08:07 +0000 (Sat, 08 Jan 2011)
Log Message:
-----------
fixed widemode a bit, changed optionparser, changed input handling (giving --id option)
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdInterface.py
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2010-12-31 14:55:52 UTC (rev 329)
+++ branches/spd-ng/src/spdCLI.py 2011-01-08 09:08:07 UTC (rev 330)
@@ -1,6 +1,6 @@
#!/usr/bin/python
-from optparse import OptionParser
+from optparse import OptionParser, OptionGroup
import sys
import re
@@ -67,7 +67,12 @@
for key in passdict:
if passdict[key][i] is None:
passdict[key][i] = ''
- sys.stdout.write(re.sub('\n','\n' + __space,str(passdict[key][i]).ljust(__keylength[key])) + '|')
+ __count = 0
+ for line in str(passdict[key][i]).split('\n'):
+ if __count > 0:
+ sys.stdout.write('\n' + __space)
+ sys.stdout.write(line.ljust(__keylength[key]) + '|')
+ __count += 1
__space = __space + ''.ljust(__keylength[key]) + ' '
sys.stdout.write('\n')
else:
@@ -76,11 +81,11 @@
print "No Results found"
# }}}
- def editEntry(self,__passdict):
+ def editEntry(self,__passdict): # {{{
__count = len(__passdict['__ID'])
for i in range(0, __count):
print '---------------------------'
- print 'Changing Entry: ' + str(__passdict['__ID'][i]) + '\nENTER for no changes.'
+ print 'Changing Entry with ID: ' + str(__passdict['__ID'][i]) + '\nENTER for no changes.'
for __column in __passdict:
__input = ''
if __column != '__ID':
@@ -90,6 +95,7 @@
if __input != '':
__passdict[__column][i] = __input
return __passdict
+ # }}}
def createEntry(self,columns): # {{{
Entry = {}
@@ -114,27 +120,37 @@
default=False,
help = "Add an Entry")
+ 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 ="Entries to delete")
+ help ="Delete given Entries")
- parser.add_option( "-e", "--edit",
- action = "store_true",
- dest ="editEntry",
- help ="Entries to edit (by id)")
-
- parser.add_option( "-i", "--delete-id",
- action = "store_true",
- dest ="deleteID",
- default = False,
- help ="ID(s) to delete")
+ group = OptionGroup(parser, "Input Manipulation")
- #parser.add_option( "--id",
- # dest ="id",
- # help ="Show Password by ID")
+ group.add_option( "--id",
+ action="store_true",
+ dest ="byid",
+ default=False,
+ help ="Handle Input given as ID(s)")
+ parser.add_option_group(group)
+
+ 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)")
+
+ parser.add_option_group(group)
+
#parser.add_option( "--add-column",
# metavar="Collumn",
# dest = "addcolumn",
@@ -147,11 +163,6 @@
# default=False,
# help = "print Password only of first match, usefull for piping (e.g. in rdesktop)")
#
- parser.add_option( "-w", "--wide",
- action="store_true",
- dest = "widemode",
- default=False,
- help = "print output in wide mode (means as a table)")
#parser.add_option( "-l", "--local",
# action="store_true",
@@ -163,31 +174,33 @@
# dest = "passfile",
# help = "do not use the confgured passfile but the one given here")
- parser.add_option( "--add-columns",
+ group = OptionGroup(parser, "Columns Manipulation")
+
+ group.add_option( "--add-columns",
action="store_true",
dest = "addColumn",
default=False,
- help = "Add Column(s)")
+ help = "Add given Column(s)")
- parser.add_option( "--delete-columns",
+ group.add_option( "--delete-columns",
action = "store_true",
dest ="deleteColumn",
default = False,
- help ="Column(s) to delete")
+ help ="Delete Columns given")
+ parser.add_option_group(group)
+
(options, args) = parser.parse_args()
if options.addEntry:
return ["addEntry", args]
elif options.deleteEntry:
- return ["deleteEntry", args]
+ return ["deleteEntry", [ options.byid, args]]
elif options.editEntry:
return ["editEntry", args]
- elif options.deleteID:
- return ["deleteID", args]
+
elif options.deleteColumn:
return ["deleteColumn", args]
-
elif options.addColumn:
return ["addColumn", args]
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2010-12-31 14:55:52 UTC (rev 329)
+++ branches/spd-ng/src/spdCore.py 2011-01-08 09:08:07 UTC (rev 330)
@@ -6,6 +6,7 @@
coreobject = spdCore.Core()'''
import sqlite3
+import re
class Core(object):
@@ -47,7 +48,10 @@
if byid:
for __id in SearchList:
- query += '__ID = ' + __id + ' or '
+ 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:
@@ -91,8 +95,10 @@
# }}}
def delEntry(self,ID): # {{{
- query = 'delete from '+ self.ConfigSection +' where __ID='+str(ID)
- self.dbc.execute(query)
+ for __id in ID:
+ query = 'delete from '+ self.ConfigSection +' where __ID=\'' + str(__id) + '\''
+ self.dbc.execute(query)
+
self.db.commit()
# }}}
@@ -101,17 +107,14 @@
for i in range(0, len(__passdict['__ID'])):
for __column in __passdict:
if __column != '__ID':
- print __column
query += __column + ' = \'' + __passdict[__column][i] + '\', '
query = query[0:-2]
query += ' WHERE __ID = ' + str(__passdict['__ID'][i])
- print query
self.dbc.execute(query)
query = 'UPDATE ' + self.ConfigSection + ' SET '
self.db.commit()
# }}}
-
def getColumns(self,showid=True): # {{{
query = "pragma Table_info('" + self.ConfigSection + "')"
self.dbc.execute(query)
@@ -165,7 +168,7 @@
DROP TABLE """ + self.ConfigSection + """_backup;
""")
self.db.commit()
- # }}}
+ # }}}a
# EOF
# vim:foldmethod=marker:tabstop=3:autoindent:shiftwidth=3
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2010-12-31 14:55:52 UTC (rev 329)
+++ branches/spd-ng/src/spdInterface.py 2011-01-08 09:08:07 UTC (rev 330)
@@ -122,26 +122,18 @@
self.__client.printPasswords(passdict)
# }}}
- def deleteID(self,ids): # {{{
- if not ids:
- self.__ErrorHandler('deleteID()','No ID to delete given')
- if type(ids).__name__ != 'list':
- if type(ids).__name__ == 'int':
- ids = str(ids)
- ids = string.split(ids)
- for id in ids:
- self.__core.delEntry(id)
- # }}}
+ def deleteEntry(self, values): # {{{
+ byid, searchString = values
+ __passdict = self.__findPasswords(searchString,byid)
+
+ if len(__passdict) == 0:
+ self.__ErrorHandler('deleteEntry','No matches found')
- def deleteEntry(self,searchString): # {{{
- __passdict = self.__findPasswords(searchString)
- if len(__passdict) > 1:
+ if len(__passdict['__ID']) > 1:
print str(__passdict)
- elif len(__passdict) > 0:
+ else:
print str(__passdict)
self.__core.delEntry(__passdict['__ID'])
- else:
- self.__ErrorHandler('deleteEntry','No matches found')
# }}}
def editEntry(self,ids): # {{{
@@ -155,7 +147,10 @@
def deleteColumn(self,columns): # {{{
for column in columns:
- self.__core.delColumn(column)
+ if column in self.__core.getColumns(showid=False):
+ self.__core.delColumn(column)
+ else:
+ self.__ErrorHandler('deleteColumn','column ' + column + ' is not part of the passwordfile')
# }}}
def addColumn(self,columns): # {{{
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Z3...@us...> - 2010-12-31 14:55:58
|
Revision: 329
http://spd.svn.sourceforge.net/spd/?rev=329&view=rev
Author: Z3po
Date: 2010-12-31 14:55:52 +0000 (Fri, 31 Dec 2010)
Log Message:
-----------
Added function to edit Entries
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2010-12-29 22:07:08 UTC (rev 328)
+++ branches/spd-ng/src/spdCLI.py 2010-12-31 14:55:52 UTC (rev 329)
@@ -9,6 +9,7 @@
Resistance is futile"""
__outmode = None
+ __version = '0.3-alpha'
def __ErrorHandler(self,function,message): # {{{
"""ErrorHandler of the Client Module.
@@ -75,6 +76,21 @@
print "No Results found"
# }}}
+ def editEntry(self,__passdict):
+ __count = len(__passdict['__ID'])
+ for i in range(0, __count):
+ print '---------------------------'
+ print 'Changing Entry: ' + 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 __input != '':
+ __passdict[__column][i] = __input
+ return __passdict
+
def createEntry(self,columns): # {{{
Entry = {}
print "Adding a new Entry to our passfile"
@@ -87,21 +103,28 @@
def parseArgs(self,version): # {{{
parser = OptionParser( "%prog [Options] [Keywords]",
description = "SPD - Simple Password Displayer - CLI",
- version = "SPD " + version,
+ version = """spdCore """ + version +
+ """\nspdCLI """ + self.__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( "-d", "--delete",
action = "store_true",
- dest ="delete",
+ dest ="deleteEntry",
default = False,
help ="Entries to delete")
- #parser.add_option( "-e", "--edit",
- # metavar="ID",
- # dest ="edit",
- # help ="ID to edit")
- #
+ parser.add_option( "-e", "--edit",
+ action = "store_true",
+ dest ="editEntry",
+ help ="Entries to edit (by id)")
+
parser.add_option( "-i", "--delete-id",
action = "store_true",
dest ="deleteID",
@@ -111,12 +134,6 @@
#parser.add_option( "--id",
# dest ="id",
# help ="Show Password by ID")
- #
- parser.add_option( "-a", "--add",
- action="store_true",
- dest = "add",
- default=False,
- help = "Add an Entry")
#parser.add_option( "--add-column",
# metavar="Collumn",
@@ -160,10 +177,12 @@
(options, args) = parser.parse_args()
- if options.add:
+ if options.addEntry:
return ["addEntry", args]
- elif options.delete:
+ elif options.deleteEntry:
return ["deleteEntry", args]
+ elif options.editEntry:
+ return ["editEntry", args]
elif options.deleteID:
return ["deleteID", args]
elif options.deleteColumn:
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2010-12-29 22:07:08 UTC (rev 328)
+++ branches/spd-ng/src/spdCore.py 2010-12-31 14:55:52 UTC (rev 329)
@@ -6,7 +6,6 @@
coreobject = spdCore.Core()'''
import sqlite3
-import atexit
class Core(object):
@@ -42,21 +41,27 @@
# }}}
- def searchEntry(self,SearchList): # {{{
+ def searchEntry(self,SearchList,byid=False): # {{{
query = 'select * from ' + self.ConfigSection + ' where '
- # Build the where-clause
- for pattern in SearchList:
- query += '('
+ if byid:
+ for __id in SearchList:
+ query += '__ID = ' + __id + ' or '
+ query = query[0:-3]
- for i in self.getColumns():
- if i != self.PasswordColumn:
- query += i + " like '%" + pattern + "%' or "
+ else:
+ # Build the where-clause
+ for pattern in SearchList:
+ query += '('
- query = query[0:-4] + ') and '
- query = query[0:-5]
+ for i in self.getColumns():
+ if i != self.PasswordColumn:
+ query += i + " like '%" + pattern + "%' or "
+ query = query[0:-4] + ') and '
+ query = query[0:-5]
+
# Execute the query
self.dbc.execute(query)
@@ -91,6 +96,22 @@
self.db.commit()
# }}}
+ def editEntry(self,__passdict): # {{{
+ query = 'UPDATE ' + self.ConfigSection + ' SET '
+ for i in range(0, len(__passdict['__ID'])):
+ for __column in __passdict:
+ if __column != '__ID':
+ print __column
+ query += __column + ' = \'' + __passdict[__column][i] + '\', '
+ query = query[0:-2]
+ query += ' WHERE __ID = ' + str(__passdict['__ID'][i])
+ print query
+ self.dbc.execute(query)
+ query = 'UPDATE ' + self.ConfigSection + ' SET '
+ self.db.commit()
+ # }}}
+
+
def getColumns(self,showid=True): # {{{
query = "pragma Table_info('" + self.ConfigSection + "')"
self.dbc.execute(query)
@@ -106,7 +127,7 @@
def addColumn(self,columnname): # {{{
if columnname in self.getColumns(showid=True):
- self.__ErrorHandler('addColumn','Column already exists')
+ self.__ErrorHandler('addColumn','Column \"' + columnname + '\" already exists')
query='alter table ' + self.ConfigSection + ' add column ' + columnname + ' text '
self.db.execute(query)
self.db.commit()
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2010-12-29 22:07:08 UTC (rev 328)
+++ branches/spd-ng/src/spdInterface.py 2010-12-31 14:55:52 UTC (rev 329)
@@ -7,8 +7,11 @@
Interface.main()
or force a clientmode with:
- Interface = spdInterface.Interface('CLI')'''
+ Interface = spdInterface.Interface('CLI')
+if building your own interface, name it spd"whatever" and pass "whatever"
+to the Interface Class. The Module must be in pythons include path.'''
+
from sys import exit
import os
import string
@@ -97,7 +100,7 @@
'clientmode' : clientmode })
# }}}
- def __findPasswords(self,searchString): # {{{
+ def __findPasswords(self,searchString,byid=False): # {{{
"""Find the passwords by searchlist/searchstring handed.
print the results in CLIENTMODE.
# searchlist: optional string or list of keywords to search for."""
@@ -109,7 +112,7 @@
if len(searchlist) == 0:
searchlist = ['%',]
- passdict = self.__core.searchEntry(searchlist)
+ passdict = self.__core.searchEntry(searchlist,byid)
return passdict
# }}}
@@ -141,6 +144,15 @@
self.__ErrorHandler('deleteEntry','No matches found')
# }}}
+ def editEntry(self,ids): # {{{
+ __passdict = self.__findPasswords(ids,byid=True)
+ if len(__passdict) > 0:
+ __newpassdict = self.__client.editEntry(__passdict)
+ self.__core.editEntry(__newpassdict)
+ else:
+ self.__ErrorHandler('editEntry','no matches for ' + str(ids) + 'found')
+ # }}}
+
def deleteColumn(self,columns): # {{{
for column in columns:
self.__core.delColumn(column)
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.
|
|
From: <Z3...@us...> - 2010-12-29 22:07:14
|
Revision: 328
http://spd.svn.sourceforge.net/spd/?rev=328&view=rev
Author: Z3po
Date: 2010-12-29 22:07:08 +0000 (Wed, 29 Dec 2010)
Log Message:
-----------
bugfix. accidentially killed PRIMARY KEY in delColumn function of spdCore
Modified Paths:
--------------
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2010-12-28 21:46:06 UTC (rev 327)
+++ branches/spd-ng/src/spdCore.py 2010-12-29 22:07:08 UTC (rev 328)
@@ -10,11 +10,6 @@
class Core(object):
- # Writes back to the Store
- def __commit(self): # {{{
- self.db.commit()
- #}}}
-
# create the database from the stuff out of the store
def __init__(self,ConfigSection='Main',PasswordColumn='Password'): # {{{
self.ConfigSection = ConfigSection
@@ -24,7 +19,6 @@
self.dbc = self.db.cursor()
self.deletedColumns = []
- atexit.register(self.__commit) # Make Sure to Write back changes to sqldb exiting
# }}}
def __ErrorHandler(self,function,message): # {{{
@@ -74,7 +68,6 @@
except KeyError:
result[j] = [i[j]]
-
return result
# }}}
@@ -89,17 +82,16 @@
query += cols[0:-2] + ') VALUES ( ' + vals[0:-2] + ')'
self.dbc.execute(query,NewDict)
-
+ self.db.commit()
# }}}
def delEntry(self,ID): # {{{
query = 'delete from '+ self.ConfigSection +' where __ID='+str(ID)
self.dbc.execute(query)
-
+ self.db.commit()
# }}}
def getColumns(self,showid=True): # {{{
-
query = "pragma Table_info('" + self.ConfigSection + "')"
self.dbc.execute(query)
@@ -109,9 +101,7 @@
continue
if i['name'] not in self.deletedColumns:
result.append(i['name'])
-
return result
-
# }}}
def addColumn(self,columnname): # {{{
@@ -119,14 +109,26 @@
self.__ErrorHandler('addColumn','Column 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 __column == '__ID':
+ __newcolumn = __column + ' INTEGER PRIMARY KEY'
+ else:
+ __newcolumn = __column + ' text'
+
+ if __newcolumns == '':
+ __newcolumns = __newcolumn
+ else:
+ __newcolumns = __newcolumns + ',' + __newcolumn
+
if __columns == '':
__columns = __column
else:
@@ -134,13 +136,14 @@
# it's not that easy, to delete a column in SQLite
self.dbc.executescript("""
- CREATE TEMPORARY TABLE """ + self.ConfigSection + """_backup(""" + __columns + """);
+ 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 + """(""" + __columns + """);
+ CREATE TABLE """ + self.ConfigSection + """(""" + __newcolumns + """);
INSERT INTO """ + self.ConfigSection + """ SELECT """ + __columns + """ FROM """ + self.ConfigSection + """_backup;
DROP TABLE """ + self.ConfigSection + """_backup;
""")
+ self.db.commit()
# }}}
# EOF
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.
|
|
From: <Z3...@us...> - 2010-12-28 21:46:12
|
Revision: 327
http://spd.svn.sourceforge.net/spd/?rev=327&view=rev
Author: Z3po
Date: 2010-12-28 21:46:06 +0000 (Tue, 28 Dec 2010)
Log Message:
-----------
added function to delete and add columns
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2010-12-27 22:31:11 UTC (rev 326)
+++ branches/spd-ng/src/spdCLI.py 2010-12-28 21:46:06 UTC (rev 327)
@@ -75,7 +75,6 @@
print "No Results found"
# }}}
-
def createEntry(self,columns): # {{{
Entry = {}
print "Adding a new Entry to our passfile"
@@ -108,7 +107,7 @@
dest ="deleteID",
default = False,
help ="ID(s) to delete")
-
+
#parser.add_option( "--id",
# dest ="id",
# help ="Show Password by ID")
@@ -118,7 +117,7 @@
dest = "add",
default=False,
help = "Add an Entry")
-
+
#parser.add_option( "--add-column",
# metavar="Collumn",
# dest = "addcolumn",
@@ -147,6 +146,18 @@
# dest = "passfile",
# help = "do not use the confgured passfile but the one given here")
+ parser.add_option( "--add-columns",
+ action="store_true",
+ dest = "addColumn",
+ default=False,
+ help = "Add Column(s)")
+
+ parser.add_option( "--delete-columns",
+ action = "store_true",
+ dest ="deleteColumn",
+ default = False,
+ help ="Column(s) to delete")
+
(options, args) = parser.parse_args()
if options.add:
@@ -155,7 +166,12 @@
return ["deleteEntry", args]
elif options.deleteID:
return ["deleteID", args]
+ elif options.deleteColumn:
+ return ["deleteColumn", args]
+ elif options.addColumn:
+ return ["addColumn", args]
+
elif options.widemode:
self.__outmode = 'wide'
else:
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2010-12-27 22:31:11 UTC (rev 326)
+++ branches/spd-ng/src/spdCore.py 2010-12-28 21:46:06 UTC (rev 327)
@@ -27,6 +27,18 @@
atexit.register(self.__commit) # Make Sure to Write back changes to sqldb exiting
# }}}
+ 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):
@@ -102,16 +114,33 @@
# }}}
- def addColumn(self,Name): # {{{
- query='alter table ' + self.ConfigSection + ' add column ' + Name + ' text '
+ def addColumn(self,columnname): # {{{
+ if columnname in self.getColumns(showid=True):
+ self.__ErrorHandler('addColumn','Column already exists')
+ query='alter table ' + self.ConfigSection + ' add column ' + columnname + ' text '
self.db.execute(query)
# }}}
- def delColumn(self,Name): # {{{
- # it's not possible, to delete a column in SQLite
- self.deletedColumns.append(Name)
+ def delColumn(self,columnname): # {{{
+ __columns = ''
+ for __column in self.getColumns(showid=True):
+ if __column == columnname and columnname != '__ID':
+ continue
+ 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(""" + __columns + """);
+ INSERT INTO """ + self.ConfigSection + """_backup SELECT """ + __columns + """ FROM """ + self.ConfigSection + """;
+ DROP TABLE """ + self.ConfigSection + """;
+ CREATE TABLE """ + self.ConfigSection + """(""" + __columns + """);
+ INSERT INTO """ + self.ConfigSection + """ SELECT """ + __columns + """ FROM """ + self.ConfigSection + """_backup;
+ DROP TABLE """ + self.ConfigSection + """_backup;
+ """)
# }}}
# EOF
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2010-12-27 22:31:11 UTC (rev 326)
+++ branches/spd-ng/src/spdInterface.py 2010-12-28 21:46:06 UTC (rev 327)
@@ -141,6 +141,16 @@
self.__ErrorHandler('deleteEntry','No matches found')
# }}}
+ def deleteColumn(self,columns): # {{{
+ for column in columns:
+ self.__core.delColumn(column)
+ # }}}
+
+ def addColumn(self,columns): # {{{
+ for column in columns:
+ self.__core.addColumn(column)
+ # }}}
+
def addEntry(self, args): # {{{
Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
self.__core.addEntry(Entry)
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.
|
|
From: <Z3...@us...> - 2010-12-27 22:31:18
|
Revision: 326
http://spd.svn.sourceforge.net/spd/?rev=326&view=rev
Author: Z3po
Date: 2010-12-27 22:31:11 +0000 (Mon, 27 Dec 2010)
Log Message:
-----------
code cleanup and little improvements
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/spdCore.py
branches/spd-ng/src/spdDefaults.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2010-12-25 11:25:43 UTC (rev 325)
+++ branches/spd-ng/src/spdCLI.py 2010-12-27 22:31:11 UTC (rev 326)
@@ -75,6 +75,7 @@
print "No Results found"
# }}}
+
def createEntry(self,columns): # {{{
Entry = {}
print "Adding a new Entry to our passfile"
Modified: branches/spd-ng/src/spdCore.py
===================================================================
--- branches/spd-ng/src/spdCore.py 2010-12-25 11:25:43 UTC (rev 325)
+++ branches/spd-ng/src/spdCore.py 2010-12-27 22:31:11 UTC (rev 326)
@@ -1,5 +1,10 @@
-#!/usr/bin/python
+'''spdCore Module.
+ Handles the Datastore of SPD.
+ Usage:
+ import spdCore
+ coreobject = spdCore.Core()'''
+
import sqlite3
import atexit
Modified: branches/spd-ng/src/spdDefaults.py
===================================================================
--- branches/spd-ng/src/spdDefaults.py 2010-12-25 11:25:43 UTC (rev 325)
+++ branches/spd-ng/src/spdDefaults.py 2010-12-27 22:31:11 UTC (rev 326)
@@ -1,55 +1,49 @@
-#!/usr/bin/python
+"""This is the Defaults Configuration Module
+ Trying to create the defaults"""
import spdConfig
import os
-class Defaults(object): # {{{
- """This is the Defaults Configuration Module
- Trying to create the defaults"""
+def __ErrorHandler(function, message): # {{{
+ '''ErrorHandler of the Defaults Module.
+ # function: the function who called the ErrorHandler
+ # message: means the \'Exception\' to throw'''
+ print '################################################'
+ print 'spdDefaults ErrorHandler.'
+ print 'ERRORFUNCTION: ' + function
+ print 'ERRORMESSAGE: ' + message
+ print '################################################'
+ sys.exit(2)
+# }}}
- spddir = os.path.expanduser('~/.spd/')
+def __oldSPDCheck(): # {{{
+ '''Checks if a old spd configuration file is there and tries to mutate it'''
+ __oldspdconfig = '~/.spd/spd.conf'
+ if os.access(os.path.expanduser(__oldspdconfig), os.R_OK):
+ print 'old config found!'
+ return True, __oldspdconfig
+ return False, None
+# }}}
- def __ErrorHandler(self, function, message): # {{{
- '''ErrorHandler of the Defaults Module.
- # function: the function who called the ErrorHandler
- # message: means the \'Exception\' to throw'''
- print '################################################'
- print 'spdDefaults ErrorHandler.'
- print 'ERRORFUNCTION: ' + function
- print 'ERRORMESSAGE: ' + message
- print '################################################'
- sys.exit(2)
- # }}}
-
- def __oldSPDCheck(self): # {{{
- __oldspdconfig = '~/.spd/spd.conf'
- if os.access(os.path.expanduser(__oldspdconfig), os.R_OK):
- print 'old config found!'
- return True, __oldspdconfig
- return False, None
- # }}}
-
- def createDefaultConfig(self,config): # {{{
- """Create the default config here.
- # config: the configparser to use"""
-
- print 'Checking if we are an upgrade first...'
- __found, __oldconfig = self.__oldSPDCheck()
- if __found == True:
- __input = ''
- while __input is not 'y' and __input is not 'n':
- __input = raw_input('Shall i try to convert the old Configfile?(y|n):')
- if __input == 'y':
- print 'Trying to convert...'
- print 'NOT YET IMPLEMENTED'
- else:
- __input = raw_input('Going to create default config now...[ENTER]')
- config.addConfigSection('Main')
- config.setConfigVersion('0.3-alpha')
- config.setClientmode('CLI')
- __input = raw_input('Done. Back to normal. [ENTER]')
- # }}}
-
+def createDefaultConfig(config): # {{{
+ """Create the default config here.
+ # config: the configparser to use"""
+
+ print 'Checking if we are an upgrade first...'
+ __found, __oldconfig = __oldSPDCheck()
+ if __found == True:
+ __input = ''
+ while __input is not 'y' and __input is not 'n':
+ __input = raw_input('Shall i try to convert the old Configfile?(y|n):')
+ if __input == 'y':
+ print 'Trying to convert...'
+ print 'NOT YET IMPLEMENTED'
+ else:
+ __input = raw_input('Going to create default config now...[ENTER]')
+ config.addConfigSection('Main')
+ config.setConfigVersion('0.3-alpha')
+ config.setClientmode('CLI')
+ __input = raw_input('Done. Back to normal. [ENTER]')
# }}}
# EOF
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2010-12-25 11:25:43 UTC (rev 325)
+++ branches/spd-ng/src/spdInterface.py 2010-12-27 22:31:11 UTC (rev 326)
@@ -1,15 +1,28 @@
-#!/usr/bin/python
+'''spdInterface Module.
-import spdConfig
-import spdDefaults
+The Modules handles all the exchange between user and spdCore.
+Usage:
+ import spdInterface
+ Interface = spdInterface.Interface()
+ Interface.main()
+
+or force a clientmode with:
+ Interface = spdInterface.Interface('CLI')'''
+
+from sys import exit
import os
-import spdCore
import string
-from sys import exit
+try:
+ import spdConfig
+ import spdDefaults
+ import spdCore
+except ImportError:
+ print 'spd not installed. Missing Modules.'
+ exit(2)
class Interface(object): # {{{
"""The Interface Module.
- Connection between Output and Core."""
+ Interface between client and Core."""
__spddir = os.path.expanduser('~/.spd/')
__version = None
__client = None
@@ -53,19 +66,22 @@
"""Do initial checks"""
if not os.access(self.__spddir, os.F_OK):
- os.mkdir(self.__spddir)
+ try:
+ os.mkdir(self.__spddir)
+ except Exception, e:
+ self.__ErrorHandler('__startupCheck','Could not create ' + self.__spddir + ' Exception: ' + str(e))
__config = spdConfig.Config()
reval, __version = __config.getConfigVersion(raw=True)
if reval > 0 and reval < 64:
- Defaults = spdDefaults.Defaults()
- Defaults.createDefaultConfig(__config)
+ spdDefaults.createDefaultConfig(__config)
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')
__version = __config.getConfigVersion()
@@ -73,6 +89,7 @@
if reval > 0:
print 'Clientmode not found...setting it to CLI\n'
+ __input = raw_input('Press any key')
__config.setClientmode('CLI')
clientmode = __config.getClientmode()
@@ -80,7 +97,7 @@
'clientmode' : clientmode })
# }}}
- def findPasswords(self,searchString='%'): # {{{
+ def __findPasswords(self,searchString): # {{{
"""Find the passwords by searchlist/searchstring handed.
print the results in CLIENTMODE.
# searchlist: optional string or list of keywords to search for."""
@@ -93,11 +110,12 @@
if len(searchlist) == 0:
searchlist = ['%',]
passdict = self.__core.searchEntry(searchlist)
+
return passdict
# }}}
def printPasswords(self,searchString='%'): # {{{
- passdict = self.findPasswords(searchString)
+ passdict = self.__findPasswords(searchString)
self.__client.printPasswords(passdict)
# }}}
@@ -113,10 +131,14 @@
# }}}
def deleteEntry(self,searchString): # {{{
- passdict = self.findPasswords(searchString)
- print str(passdict)
- for id in passdict["__ID"]:
- self.__core.delEntry(id)
+ __passdict = self.__findPasswords(searchString)
+ if len(__passdict) > 1:
+ print str(__passdict)
+ elif len(__passdict) > 0:
+ print str(__passdict)
+ self.__core.delEntry(__passdict['__ID'])
+ else:
+ self.__ErrorHandler('deleteEntry','No matches found')
# }}}
def addEntry(self, args): # {{{
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.
|
|
From: <Z3...@us...> - 2010-12-25 11:25:51
|
Revision: 325
http://spd.svn.sourceforge.net/spd/?rev=325&view=rev
Author: Z3po
Date: 2010-12-25 11:25:43 +0000 (Sat, 25 Dec 2010)
Log Message:
-----------
introducing --wide mode
Modified Paths:
--------------
branches/spd-ng/src/spdCLI.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdCLI.py
===================================================================
--- branches/spd-ng/src/spdCLI.py 2010-12-25 00:35:22 UTC (rev 324)
+++ branches/spd-ng/src/spdCLI.py 2010-12-25 11:25:43 UTC (rev 325)
@@ -1,6 +1,8 @@
#!/usr/bin/python
from optparse import OptionParser
+import sys
+import re
class Cli(object): # {{{
"""This is the Cli Module.
@@ -8,12 +10,25 @@
__outmode = None
+ def __ErrorHandler(self,function,message): # {{{
+ """ErrorHandler of the Client Module.
+ # function: the function which throws the error
+ # message: means the \'Exception\' to throw"""
+ print "################################################"
+ print "spdCli ErrorHandler."
+ print "ERRORFUNCTION: " + function
+ print "ERRORMESSAGE: " + message
+ print "################################################"
+ exit(2)
+ # }}}
+
def printPasswords(self,passdict): # {{{
"""Print the passwords out of a dictionary.
# passdict: the dictionary full of passwords"""
+ __keylength = {}
if type(passdict).__name__ != 'NoneType' and len(passdict) != 0:
- if self.__outmode == 'lines':
+ if self.__outmode == 'line':
length = 0
for key in passdict.keys():
if length < len(key):
@@ -30,7 +45,32 @@
print key.ljust(length) + ': '
print ""
elif self.__outmode == 'wide':
- print 'NOT YET IMPLEMENTED...SORRY'
+ 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 len(str(value)) > __keylength[key]:
+ __keylength[key] = len(str(value))
+
+ for key in passdict:
+ sys.stdout.write(key.ljust(__keylength[key]) + '|')
+ sys.stdout.write('\n')
+
+ __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] = ''
+ sys.stdout.write(re.sub('\n','\n' + __space,str(passdict[key][i]).ljust(__keylength[key])) + '|')
+ __space = __space + ''.ljust(__keylength[key]) + ' '
+ sys.stdout.write('\n')
+ else:
+ self.__ErrorHandler('printPasswords', 'output mode unknown')
else:
print "No Results found"
# }}}
@@ -45,7 +85,6 @@
# }}}
def parseArgs(self,version): # {{{
- __ouput="lines"
parser = OptionParser( "%prog [Options] [Keywords]",
description = "SPD - Simple Password Displayer - CLI",
version = "SPD " + version,
@@ -119,15 +158,11 @@
elif options.widemode:
self.__outmode = 'wide'
else:
- self.__outmode = 'lines'
+ self.__outmode = 'line'
return ["printPasswords", args]
# }}}
- def main(self,options,args): # {{{
- pass
- # }}}
-
# }}}
# EOF
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.
|
|
From: <Z3...@us...> - 2010-12-25 00:35:29
|
Revision: 324
http://spd.svn.sourceforge.net/spd/?rev=324&view=rev
Author: Z3po
Date: 2010-12-25 00:35:22 +0000 (Sat, 25 Dec 2010)
Log Message:
-----------
little code cleanup
Modified Paths:
--------------
branches/spd-ng/src/spdConfig.py
branches/spd-ng/src/spdDefaults.py
branches/spd-ng/src/spdInterface.py
branches/spd-ng/src/test.db
Modified: branches/spd-ng/src/spdConfig.py
===================================================================
--- branches/spd-ng/src/spdConfig.py 2010-12-24 14:33:23 UTC (rev 323)
+++ branches/spd-ng/src/spdConfig.py 2010-12-25 00:35:22 UTC (rev 324)
@@ -7,6 +7,7 @@
class Config(object): # {{{
'''This is the Configuration Module
You can read or set config options'''
+ __configfile = None
ReturnCodes = { 2 : 'Missing ConfigFile',
4 : 'ConfigFile not Readable',
@@ -15,8 +16,8 @@
32 : 'Section not found',
64 : 'Option not found' }
- def __init__(self, conffile='~/.spd/config'): # {{{
- self.configfile = os.path.expanduser(conffile)
+ def __init__(self, configfile='~/.spd/config'): # {{{
+ self.__configfile = os.path.expanduser(configfile)
# }}}
def __ErrorHandler(self,message): # {{{
@@ -24,7 +25,7 @@
# message: means the \'Exception\' to throw"""
print "################################################"
print "spdConfig ErrorHandler."
- print "Configfile: " + self.configfile
+ print "Configfile: " + self.__configfile
print "ERRORMESSAGE: " + message
print "################################################"
sys.exit(2)
@@ -33,7 +34,7 @@
def __checkConfigFileExist(self): # {{{
"""Does the Config file exist?"""
- if os.access(self.configfile, os.F_OK):
+ if os.access(self.__configfile, os.F_OK):
return 0
else:
return 2
@@ -49,8 +50,8 @@
return reval, config
- if os.access(self.configfile,os.R_OK):
- config.read(self.configfile)
+ if os.access(self.__configfile,os.R_OK):
+ config.read(self.__configfile)
return 0,config
else:
return 4, config
@@ -63,14 +64,14 @@
if reval > 0:
try:
- configfile = open(self.configfile, 'wb')
+ 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')
+ if os.access(self.__configfile,os.W_OK):
+ configfile = open(self.__configfile, 'wb')
else:
return 8, None
Modified: branches/spd-ng/src/spdDefaults.py
===================================================================
--- branches/spd-ng/src/spdDefaults.py 2010-12-24 14:33:23 UTC (rev 323)
+++ branches/spd-ng/src/spdDefaults.py 2010-12-25 00:35:22 UTC (rev 324)
@@ -24,17 +24,30 @@
def __oldSPDCheck(self): # {{{
__oldspdconfig = '~/.spd/spd.conf'
if os.access(os.path.expanduser(__oldspdconfig), os.R_OK):
- print 'old config found'
+ print 'old config found!'
+ return True, __oldspdconfig
+ return False, None
# }}}
def createDefaultConfig(self,config): # {{{
"""Create the default config here.
# config: the configparser to use"""
- self.__oldSPDCheck()
- config.addConfigSection('Main')
- config.setConfigVersion('0.3-alpha')
- config.setClientmode('CLI')
+ print 'Checking if we are an upgrade first...'
+ __found, __oldconfig = self.__oldSPDCheck()
+ if __found == True:
+ __input = ''
+ while __input is not 'y' and __input is not 'n':
+ __input = raw_input('Shall i try to convert the old Configfile?(y|n):')
+ if __input == 'y':
+ print 'Trying to convert...'
+ print 'NOT YET IMPLEMENTED'
+ else:
+ __input = raw_input('Going to create default config now...[ENTER]')
+ config.addConfigSection('Main')
+ config.setConfigVersion('0.3-alpha')
+ config.setClientmode('CLI')
+ __input = raw_input('Done. Back to normal. [ENTER]')
# }}}
# }}}
Modified: branches/spd-ng/src/spdInterface.py
===================================================================
--- branches/spd-ng/src/spdInterface.py 2010-12-24 14:33:23 UTC (rev 323)
+++ branches/spd-ng/src/spdInterface.py 2010-12-25 00:35:22 UTC (rev 324)
@@ -10,33 +10,32 @@
class Interface(object): # {{{
"""The Interface Module.
Connection between Output and Core."""
- spddir = os.path.expanduser('~/.spd/')
- config = spdConfig.Config()
- version = None
- client = None
- core = None
+ __spddir = os.path.expanduser('~/.spd/')
+ __version = None
+ __client = None
+ __core = None
def __init__(self,clientmode=False): # {{{
"""init procedure"""
initcheck = self.__startupCheck()
- self.version = initcheck['version']
+ self.__version = initcheck['version']
+
if not clientmode:
clientmode = initcheck['clientmode']
del initcheck
try:
- __client = __import__('spd' + clientmode)
+ __tempclient = __import__('spd' + clientmode)
except ImportError:
- print 'clientmode \"' + clientmode + '\" not available'
- exit(2)
+ self.__ErrorHandler('__init__', 'clientmode ' + clientmode + ' not available!')
else:
- self.client = __client.Cli()
- del __client
+ self.__client = __tempclient.Cli()
+ del __tempclient
- self.core = spdCore.Core()
+ self.__core = spdCore.Core()
# }}}
def __ErrorHandler(self,function,message): # {{{
@@ -53,31 +52,31 @@
def __startupCheck(self): # {{{
"""Do initial checks"""
- if not os.access(self.spddir, os.F_OK):
- os.mkdir(spddir)
+ if not os.access(self.__spddir, os.F_OK):
+ os.mkdir(self.__spddir)
+
+ __config = spdConfig.Config()
+
+ reval, __version = __config.getConfigVersion(raw=True)
- config = self.config
-
- reval, version = config.getConfigVersion(raw=True)
-
if reval > 0 and reval < 64:
Defaults = spdDefaults.Defaults()
- Defaults.createDefaultConfig(config)
+ Defaults.createDefaultConfig(__config)
return self.__startupCheck()
elif reval == 64:
print 'ConfigVersion not found...setting Default one\n'
- config.setConfigVersion('0.3-alpha')
- version = config.getConfigVersion()
+ __config.setConfigVersion('0.3-alpha')
+ __version = __config.getConfigVersion()
- reval, clientmode = config.getClientmode(raw=True)
+ reval, clientmode = __config.getClientmode(raw=True)
if reval > 0:
print 'Clientmode not found...setting it to CLI\n'
- config.setClientmode('CLI')
- clientmode = config.getClientmode()
+ __config.setClientmode('CLI')
+ clientmode = __config.getClientmode()
- return({ 'version' : version,
+ return({ 'version' : __version,
'clientmode' : clientmode })
# }}}
@@ -93,13 +92,13 @@
if len(searchlist) == 0:
searchlist = ['%',]
- passdict = self.core.searchEntry(searchlist)
+ passdict = self.__core.searchEntry(searchlist)
return passdict
# }}}
def printPasswords(self,searchString='%'): # {{{
passdict = self.findPasswords(searchString)
- self.client.printPasswords(passdict)
+ self.__client.printPasswords(passdict)
# }}}
def deleteID(self,ids): # {{{
@@ -110,23 +109,23 @@
ids = str(ids)
ids = string.split(ids)
for id in ids:
- self.core.delEntry(id)
+ self.__core.delEntry(id)
# }}}
def deleteEntry(self,searchString): # {{{
passdict = self.findPasswords(searchString)
print str(passdict)
for id in passdict["__ID"]:
- self.core.delEntry(id)
+ self.__core.delEntry(id)
# }}}
def addEntry(self, args): # {{{
- Entry = self.client.createEntry(self.core.getColumns(showid=False))
- self.core.addEntry(Entry)
+ Entry = self.__client.createEntry(self.__core.getColumns(showid=False))
+ self.__core.addEntry(Entry)
# }}}
def main(self): # {{{
- function, value = self.client.parseArgs(self.version)
+ function, value = self.__client.parseArgs(self.__version)
getattr(self, function)(value)
# }}}
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.
|