#!/usr/bin/env python """ capture an idea to http://k0s.org/portfolio/ideas/ It is also an idea """ # TODO: # - package import optparse import os import shlex import string import sys import time import tempfile from subprocess import check_call as call # default directory to store ideas # e.g. /home/jhammel/web/site/portfolio/ideas DIRECTORY = os.path.join(os.path.expanduser('~'), 'web', 'site', 'portfolio', 'ideas') # (could also be `os.path.dirname(os.path.realpath(__file__))`) # default EDITOR from environment variable EDITOR = os.environ.get('EDITOR') class EditException(Exception): """exceptions from editing""" def edit(path, editor=None): """ open a file for interactive editing with the chosen editor - path : file path to edit - editor : command line invocation of editor """ # get editor from the environment, if not given editor = editor or os.environ.get('EDITOR') if isinstance(editor, basestring): # split command line if string (e.g. `EDITOR="emacs -nw"`) editor = shlex.split(editor.strip()) if not editor: raise EditException("editor undefined") # edit the file call(list(editor) + [path]) def main(args=sys.argv[1:]): """command line entry point""" # parse command line options usage = '%prog [options] ' parser = optparse.OptionParser(usage=usage) parser.add_option('-d', '--directory', dest='directory', default=DIRECTORY, help="directory for ideas [default: %default]") parser.add_option('-e', '--editor', dest='editor', default=EDITOR, help="editor to use") # TODO: take an idea from a file instead of forcing interactive editing options, args = parser.parse_args(args) # sanity check if not options.editor: print >> sys.stderr, "EDITOR and -e,--editor not set, aborting" time.sleep(5) parser.exit(1) # get idea (file) name if args: # TODO: take idea from path/URL optionally idea = '_'.join(args) else: idea = raw_input('What is a short name for the idea?\n') idea = '_'.join(idea.strip().split()) allowed_characters = set(string.letters + string.digits + '_-.') idea = ''.join([i for i in idea if i in allowed_characters]) if not idea: raise Exception("Filename not specified correctly") # XXX if '.' not in idea: # add a .txt extension by default idea += '.txt' # edit the file in the directory; # will err if `directory is a file, not directory if not os.path.exists(options.directory): os.makedirs(options.directory) path = os.path.join(options.directory, idea) if idea.endswith('.py') and len(idea.split()) == 1: with file(path, 'w') as f: f.write('''""" """ ''') edit(path, options.editor) # print the path print path if __name__ == '__main__': main()