##// END OF EJS Templates
Merging upstream changes from inputhook.
Merging upstream changes from inputhook.

File last commit:

r2198:f9c292a2
r2199:78b56ac5 merge
Show More
loader.py
198 lines | 6.1 KiB | text/x-python | PythonLexer
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #!/usr/bin/env python
# encoding: utf-8
"""A factory for creating configuration objects.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2009 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 import sys
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 from IPython.external import argparse
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 from IPython.utils.ipstruct import Struct
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
class ConfigLoaderError(Exception):
pass
class ConfigLoader(object):
"""A object for loading configurations from just about anywhere.
The resulting configuration is packaged as a :class:`Struct`.
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
Notes
-----
A :class:`ConfigLoader` does one thing: load a config from a source
(file, command line arguments) and returns the data as a :class:`Struct`.
There are lots of things that :class:`ConfigLoader` does not do. It does
not implement complex logic for finding config files. It does not handle
default values or merge multiple configs. These things need to be
handled elsewhere.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """
def __init__(self):
"""A base class for config loaders.
Examples
--------
>>> cl = ConfigLoader()
>>> config = cl.load_config()
>>> config
{}
"""
self.clear()
def clear(self):
self.config = Struct()
def load_config(self):
"""Load a config from somewhere, return a Struct.
Usually, this will cause self.config to be set and then returned.
"""
return self.config
class FileConfigLoader(ConfigLoader):
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 """A base class for file based configurations.
As we add more file based config loaders, the common logic should go
here.
"""
pass
class PyFileConfigLoader(FileConfigLoader):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """A config loader for pure python files.
This calls execfile on a plain python file and looks for attributes
that are all caps. These attribute are added to the config Struct.
"""
def __init__(self, filename, path='.'):
"""Build a config loader for a filename and path.
Parameters
----------
filename : str
The file name of the config file.
path : str, list, tuple
The path to search for the config file on, or a sequence of
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 paths to try in order.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 super(PyFileConfigLoader, self).__init__()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.filename = filename
self.path = path
self.full_filename = ''
self.data = None
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def load_config(self):
"""Load the config from a file and return it as a Struct."""
self._find_file()
self._read_file_as_dict()
self._convert_to_struct()
return self.config
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _find_file(self):
"""Try to find the file by searching the paths."""
Brian Granger
Added simple tests for IPython.config.loader.
r2186 if os.path.isfile(os.path.expanduser(self.filename)):
self.full_filename = os.path.expanduser(self.filename)
return
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 if self.path == '.':
self.path = [os.getcwd()]
if not isinstance(path, (list, tuple)):
raise TypeError("path must be a list or tuple, got: %r" % self.path)
for p in self.path:
if p == '.': p = os.getcwd()
Brian Granger
Added simple tests for IPython.config.loader.
r2186 full_filename = os.path.expanduser(os.path.join(p, self.filename))
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 if os.path.isfile(full_filename):
self.full_filename = full_filename
return
raise IOError("Config file does not exist in any "
"of the search paths: %r, %r" % \
(self.filename, self.path))
def _read_file_as_dict(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.data = {}
execfile(self.full_filename, self.data)
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _convert_to_struct(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 if self.data is None:
ConfigLoaderError('self.data does not exist')
for k, v in self.data.iteritems():
if k == k.upper():
self.config[k] = v
class CommandLineConfigLoader(ConfigLoader):
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 """A config loader for command line arguments.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 As we add more command line based loaders, the common logic should go
here.
"""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 class NoDefault(object): pass
NoDefault = NoDefault()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
class ArgParseConfigLoader(CommandLineConfigLoader):
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
Brian Granger
Minor changes to a few files to reflect design discussion.
r2198 arguments = ()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
def __init__(self, *args, **kw):
"""Create a config loader for use with argparse.
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 The args and kwargs arguments here are passed onto the constructor
of :class:`argparse.ArgumentParser`.
"""
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 super(CommandLineConfigLoader, self).__init__()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.args = args
self.kw = kw
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def load_config(self, args=None):
"""Parse command line arguments and return as a Struct."""
self._create_parser()
self._parse_args(args)
self._convert_to_struct()
return self.config
def _create_parser(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 self._add_arguments()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _add_arguments(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 for argument in self.arguments:
Brian Granger
Added simple tests for IPython.config.loader.
r2186 if not argument[1].has_key('default'):
argument[1]['default'] = NoDefault
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.parser.add_argument(*argument[0],**argument[1])
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _parse_args(self, args=None):
"""self.parser->self.parsed_data"""
if args is None:
self.parsed_data = self.parser.parse_args()
else:
self.parsed_data = self.parser.parse_args(args)
def _convert_to_struct(self):
"""self.parsed_data->self.config"""
self.config = Struct()
for k, v in vars(self.parsed_data).items():
if v is not NoDefault:
setattr(self.config, k, v)