Skip to content

Instantly share code, notes, and snippets.

@starenka
Created January 15, 2011 12:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starenka/780868 to your computer and use it in GitHub Desktop.
Save starenka/780868 to your computer and use it in GitHub Desktop.
shellfu - one liner dbase
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# simple shell-fu database
#
# @author: starenka
# @email: 'moc]tod[liamg].T.E[0aknerats'[::-1]
# @version: 1.3
# @since 1/14/11
# @depends sqlalchemy
import sys,os
from optparse import OptionParser
from subprocess import Popen
from sqlalchemy import create_engine,Column,Integer,String,Table,ForeignKey,or_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,relationship
engine = create_engine('sqlite:///%s/shell-fu.db'%os.path.expanduser('~'),echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
metadata = Base.metadata
tb_command_has_tag = Table('item_has_tag', metadata,
Column('item_id',Integer,ForeignKey('item.item_id',onupdate="CASCADE", ondelete="CASCADE")),
Column('tag_id', Integer,ForeignKey('tag.tag_id',onupdate="CASCADE", ondelete="CASCADE"))
)
class Item(Base):
__tablename__ = 'item'
item_id = Column(Integer,primary_key=True)
item_content = Column(String,unique=True)
tags = relationship('Tag',secondary=tb_command_has_tag,backref='items')
def __init__(self,item): self.item_content = item
def __repr__(self):
return '%s\n ✎%s'.decode('utf8')%\
(self.item_content,' ✎'.decode('utf8').join([str(tag) for tag in self.tags]))
class Tag(Base):
__tablename__ = 'tag'
tag_id = Column(Integer,primary_key=True)
tag_name = Column(String,unique=True)
def __init__(self,name):
self.tag_name = name
def __repr__(self):
return self.tag_name
metadata.create_all(engine)
session = Session()
class Output():
NOTICE_COLOR = '\033[94m'
OK_COLOR = '\033[94m'
ERROR_COLOR = '\033[91m'
EVEN_COLOR = '\033[36m'
ODD_COLOR = '\033[37m'
RESET = '\033[0;0m'
@staticmethod
def err(mess):
print '\n%s[-] %s%s'%(Output.ERROR_COLOR,mess,Output.RESET)
@staticmethod
def notice(mess):
print '\n%s[*] %s%s'%(Output.NOTICE_COLOR,mess,Output.RESET)
@staticmethod
def ok(mess):
print '\n%s[+] %s%s'%(Output.OK_COLOR,mess,Output.RESET)
@staticmethod
def line(mess,even):
return '%s%s%s'%(Output.EVEN_COLOR if even else Output.ODD_COLOR,mess,Output.RESET)
@staticmethod
def mess(mess):
print mess
class Clipboard():
@staticmethod
def paste(data,engine='k'):
if engine == '3':
cmd = ['dcop','klipper','klipper','setClipboardContents',data]
elif engine == 'k':
cmd = ['dbus-send','--type=method_call','--dest=org.kde.klipper',
'/klipper','org.kde.klipper.klipper.setClipboardContents',
'string:%s'%data]
elif engine == 'x':
cmd = "echo '%s' | xclip"%data
elif engine == 'm':
cmd = 'echo "%s" | pbcopy'%data
try:
proc = Popen(cmd,shell=False)
proc.communicate()
except Exception, e:
Output.err('An error has occured while copying data to clipboard.\n%s'%e)
def exit(mess = None):
session.commit()
if mess:
Output.notice(mess)
sys.exit()
usage = "shell-fu tag"
parser = OptionParser(usage)
parser.add_option('-a','--add',action='store_true',dest='add',default=False,help='add new item')
parser.add_option('-l','--list',action='store_true',dest='list',default=False,help='show all items')
parser.add_option('-t','--tags',action='store_true',dest='tags',default=False,help='show all tags')
(options,args) = parser.parse_args()
try:
if options.add:
item = raw_input('Your precious one-liner: ')
while not item or session.query(Item).filter(Item.item_content==item).first():
Output.err('Item is empty or already exists...')
item = raw_input('Your precious one-liner: ')
tags = ''
while not tags:
tags = raw_input('Tag it (separate tags w/ comma): ')
item = Item(item.strip())
item.tags = []
for tag in tags.replace(', ',',').split(','):
t = session.query(Tag).filter(Tag.tag_name==tag.strip()).first()
if not t:
t = Tag(tag.strip())
item.tags.append(t)
session.add(item)
exit()
if options.tags:
print ' '.join([Output.line(item,i%2==0) for i,item in enumerate(session.query(Tag).all())])
exit()
if options.list:
print '\n'.join([Output.line(item,i%2==0) for i,item in enumerate(session.query(Item).all())])
exit()
if len(sys.argv) == 2:
items = session.query(Item).filter(or_(Item.item_content.like('%%%s%%'%sys.argv[1]),
Item.tags.any(Tag.tag_name==sys.argv[1]))).all()
if items:
print '\n'.join([Output.line('[%s] %s'%(str(i).rjust(2,'0'),item),i%2==0) for i,item in enumerate(items)])
nr = ''
while not nr.isdigit() or int(nr) > len(items) or int(nr) < 0:
nr = raw_input('What item? [#]: ')
action = ''
while action not in ('k','m','x','3','e','d'):
action = raw_input('So? Should I copy item to [k]de4,[m]ac,[x] or kde[3] clipboard, edit or [d]elete it?: ').lower()
if action in ['k','m','x','3']:
item = items[int(nr)]
Clipboard.paste(item.item_content,action)
elif action == 'd':
session.delete(items[int(nr)])
elif action == 'e':
raise NotImplementedError
exit()
except KeyboardInterrupt:
exit('Bye.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment