Skip to content

Commit

Permalink
Use argparse to produce nicer CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
mwilliamson committed Oct 11, 2012
1 parent 39d9250 commit ffa38af
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 21 deletions.
34 changes: 20 additions & 14 deletions blah/commands.py
Expand Up @@ -5,24 +5,30 @@
import blah.repositories
import blah.fetcher

def find_command(name):
return commands[name]
class WhatIsThisCommand(object):
def create_parser(self, subparser):
subparser.add_argument("directory", nargs="?")

def execute(self, args):
directory = args.directory if args.directory is not None else os.getcwd()
repository = blah.repositories.find_repository(directory)
if repository is None:
print "Could not find source control repository"
else:
print "{0}+file://{1}".format(repository.type, repository.working_directory)

def what_is_this_command():
directory = sys.argv[2] if len(sys.argv) > 2 else os.getcwd()
repository = blah.repositories.find_repository(directory)
if repository is None:
print "Could not find source control repository"
else:
print "{0}+file://{1}".format(repository.type, repository.working_directory)
what_is_this_command = WhatIsThisCommand()

def fetch_command():
repository_uri = sys.argv[2]
local_path = sys.argv[3]
blah.fetcher.fetch(repository_uri, local_path)
class FetchCommand(object):
def create_parser(self, subparser):
subparser.add_argument("repository_uri", metavar="repository-uri")
subparser.add_argument("local_path", metavar="local-path")

def execute(self, args):
blah.fetcher.fetch(args.repository_uri, args.local_path)

commands = {
"whatisthis": what_is_this_command,
"what-is-this": what_is_this_command,
"fetch": fetch_command
"fetch": FetchCommand()
}
1 change: 1 addition & 0 deletions requirements.txt
@@ -1,2 +1,3 @@
argparse==1.2.1
nose==1.2.1
mock==0.8.0
20 changes: 13 additions & 7 deletions scripts/blah
@@ -1,16 +1,22 @@
#!/usr/bin/env python

import sys
import argparse
import functools

from blah.commands import find_command
from blah.commands import commands

def main():
command_name = sys.argv[1]
command = find_command(command_name)
if command is None:
print 'command not recognised: {0}'.format(command_name)
else:
command()
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

for command_name, command in commands.iteritems():
subparser = subparsers.add_parser(command_name)
subparser.set_defaults(func=command.execute)
command.create_parser(subparser)

args = parser.parse_args()
args.func(args)

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions setup.py
Expand Up @@ -15,4 +15,5 @@ def read(fname):
url='http://github.com/mwilliamson/blah',
scripts=["scripts/blah"],
packages=['blah'],
install_requires=["argparse==1.2.1"],
)

0 comments on commit ffa38af

Please sign in to comment.