Permalink
Browse files

Use argparse to produce nicer CLI

  • Loading branch information...
mwilliamson committed Oct 11, 2012
1 parent 39d9250 commit ffa38af3d5c877a190e5730f8bdf21609b3bb371
Showing with 35 additions and 21 deletions.
  1. +20 −14 blah/commands.py
  2. +1 −0 requirements.txt
  3. +13 −7 scripts/blah
  4. +1 −0 setup.py
View
@@ -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()
}
View
@@ -1,2 +1,3 @@
+argparse==1.2.1
nose==1.2.1
mock==0.8.0
View
@@ -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()
View
@@ -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.