#!/usr/bin/env python

# Parsing options from somewhere other than sys.argv with Optik.

from optik import OptionParser

def main():

    # The usual reason for wanting to parse options from somewhere other
    # than the command-line (sys.argv) is to allow the user (or
    # sysadmin) to specify default options via a config file, an
    # environment variable, or some other means.  In the real world,
    # we'd have to worry about finding, reading, and parsing that
    # external info; for this example, I'll just hard-code an argument
    # list.
    #
    # Also, in the real world you'd probably be content with Optik's
    # default expansion of %prog (in usage and version strings).  For
    # testing/illustrative purposes, though, I'm also going to supply a
    # custom value here.

    prog = "test"
    usage = "%prog [-a string] [-b int] [--foo string ...]"
    parser = OptionParser(prog=prog, usage=usage)
    parser.add_option("-a")
    parser.add_option("-b", type="int")
    parser.add_option("--foo", action="append")
    
    # First, ask for help -- but intercept Optik's sys.exit() call.
    try:
        print "parsing with --help..."
        parser.parse_args(["--help"])
    except SystemExit, err:
        print "optik called sys.exit(%r)" % err.args
    else:
        print "expected optik to exit!"
    print

    # Parse a broken command-line and show the error message.
    try:
        print "parsing with invalid options..."
        parser.parse_args(["-b", "xx"])
    except SystemExit, err:
        print "optik called sys.exit(%r)" % err.args
    else:
        print "expected an error!"
    print

    # Now parse a valid command-line and check the results.
    print "parsing with valid options..."
    args = ["-afoo", "-b", "42", "--foo", "hello", "--foo=again"]
    (options, args) = parser.parse_args(args)
    assert args == [], "args: expected empty list, got %r" % args
    assert options.a == "foo", "-a: expected 'foo', got %r" % options.a
    assert options.b == 42, "-b: expected 42, got %r" % options.b
    assert options.foo == ["hello", "again"]
    print "all good!"

main()
