degal/main.py
author Tero Marttila <terom@fixme.fi>
Wed, 10 Jun 2009 23:33:28 +0300
changeset 84 891545a38a2b
parent 76 e22d9f699081
child 87 a7a18893730d
permissions -rw-r--r--
change utils.LazyProperty to store the cached value using obj.__dict__
"""
    Main entry point for the command-line interface
"""

import gallery, commands, config as config_module

from optparse import OptionParser

def option_parser (command_name) :
    """
        Build the OptionParser that we use
    """
    
    # create parser using the given command
    parser = OptionParser(prog=command_name)
    
    # define options
    parser.add_option('-G', "--gallery-path", dest='gallery_path', help="Use DIR as the Gallery path [default: CWD]", metavar='DIR', default=None)
    parser.add_option('-R', "--read-only", dest='read_only', help="Do not attempt to modify the gallery", action="store_true", default=False)
    
    return parser

def build_config (options) :
    """
        Build a configuration object with the given options
    """
    
    # build default config
    config = config_module.Configuration()
    
    # apply options
    if options.gallery_path :
        config.gallery_path = options.gallery_path
    
    if options.read_only :
        config.read_only = True

    # XXX: load config file(s)

    return config

def load_gallery (config) :
    """
        Create the Gallery object that we are manipulating
    """
    
    # read path from config
    return gallery.Gallery(config.gallery_path, config)

def load_command (config, args) :
    """
        Figure out what command to run and with what args
    """
    
    # XXX: hardcoded
    return commands.main, args, {}

def run_command (config, gallery, command, args, kwargs) :
    """
        Run the given command
    """
    
    # setup the command execution context
    command_ctx = command.setup(config, gallery)
    
    try :
        # run it
        return command_ctx(*args, **kwargs)
    
    except :
        command_ctx.handle_error()

def main (argv) :
    """
        Main entry point
    """

    ## load commands
    #commands = load_commands()

    # build optparser
    parser = option_parser(argv[0])
    
    # parse the given argv
    options, args = parser.parse_args(argv[1:])

    # build our config
    config = build_config(options)

    # open gallery
    gallery = load_gallery(config)

    # figure out what command to run
    command, args, kwargs = load_command(config, args)

    # run the selected command
    ret = run_command(config, gallery, command, args, kwargs)
    
    if ret is None :
        # success
        return 0

    else :
        # exit with error code
        assert isinstance(ret, int)
        return ret