Exemplo n.º 1
0
def load_config(configfile=None, caller=None):
    """ Load configuration definitions.
       (This is really scary, actually. We are trusting that the 
       config.py we are taking as input is sane!) 

       If both the commandline and the parameter are 
       specified then the commandline takes precedence.
    """

    # '/home/pnijjar/watcamp/python_rss/gcal_helpers/config.py'
    # See: http://www.karoltomala.com/blog/?p=622
    DEFAULT_CONFIG_SOURCEFILE = os.path.join(
        os.getcwd(),
        'config.py',
    )

    config_location = None

    if configfile:
        config_location = configfile
    else:
        config_location = DEFAULT_CONFIG_SOURCEFILE

    # Now parse commandline options (Here??? This code smells bad.)
    parser = argparse.ArgumentParser(
        description="Generate fun RSS/newsletter feeds from "
        "Google Calendar entries.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        '-c',
        '--configfile',
        help='configuration file location',
        default=config_location,
    )

    # HACK HACK HACK. send_tweet needs to load the config file,
    # but needs an additional parameter.

    if caller == 'send_tweet':
        parser.add_argument(
            '--tweet-id',
            help='ID of file containing tweet',
            required=True,
        )

    args = parser.parse_args()
    if args.configfile:
        config_location = os.path.abspath(args.configfile)

    # http://stackoverflow.com/questions/11990556/python-how-to-make-global
    global config

    # Blargh. You can load modules from paths, but the syntax is
    # different depending on the version of python.
    # http://stackoverflow.com/questions/67631/how-to-import-a-mod
    # https://stackoverflow.com/questions/1093322/how-do-i-ch

    if sys.version_info >= (3, 5):
        import importlib.util
        spec = importlib.util.spec_from_file_location(
            'config',
            config_location,
        )
        config = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(config)
    elif sys.version_info >= (3, 3):
        # This is the only one I can test. Sad!
        from importlib.machinery import SourceFileLoader
        config = SourceFileLoader(
            'config',
            config_location,
        ).load_module()
    else:
        import imp
        config = imp.load_source(
            'config',
            config_location,
        )

    if caller == 'send_tweet' and args.tweet_id:
        config.TWEET_ID = args.tweet_id

    # Needed to send tweets
    config.CONFIG_LOCATION = config_location

    # For test harness
    return config