class JobWriter(object): """ A task that writes files in the disk. Attributes: basepath: Base path where to write files. config: Reference to the job config object. context: A dictionary with extra context variables. """ project = property(lambda _: get_config().get('options', 'project')) pyname = property(lambda _: get_config().get('options', 'pyname')) def __init__(self, config, context=None): self.basepath = os.getcwd() self.config = config self.context = dict(context or {}) def get_context(self, **kwargs): """ Return a context dictionary for rendering templates. """ kwargs = dict(self.config.get_context(), **self.context) kwargs = dict(kwargs, **kwargs) return get_context(**kwargs) def save(self): """ Saves config file. """ save_config() def write(self, template, path=None, ignore=True): """ Process contents of template and write them to the given path. If ignore is true, ignore file if it already exist. """ template = template.replace('/', os.sep) if path: path = path.replace('/', os.sep) base = os.getcwd() file = os.path.join(base, path or template) file = file[len(self.basepath) + 1:] # Prepare namespace context = self.get_context(job=self, date=datetime.datetime.now()) # Write data and fetch hash prepare_path(path or template) hash = write_template(template, context, ignore=ignore, path=path) if hash is not None: register_file(file, hash)
def require(self, name, text, default=None, section=None, action=None): """ Require that the given variable is defined in the config file. """ section = section or self.config_section value = get_config().get(section, name) if not value: if action is None and default is None: value = io.grab_input(text) elif action is None: value = io.default_input(text, default) elif action == 'yn': value = io.yn_input(text) elif action == 'ny': value = io.ny_input(text) else: raise ValueError('invalid action: %r' % action) # Save value get_config().set(self.config_section, name, value) return value
def __setattr__(self, attr, value): if attr.startswith('_'): self.__dict__[attr] = value else: get_config().set(self.config_section, attr, value)
def __getattr__(self, attr): try: return get_config().get(self.config_section, attr) except KeyError: raise AttributeError
def __init__(self, config_section, **kwargs): self.__dict__['config_section'] = config_section kwargs = {k: v for k, v in kwargs.items() if v} cfg = get_config() for k, v in kwargs.items(): cfg.set(config_section, k, v)
def config(tempdir): yield get_config() config_mod.GLOBAL_CONFIG = None config_mod.CONFIG_DIR = None