def test_options(self): configfile = open(self.filename, 'w') configfile.writelines( ['[a]\n', 'option = x\n', '[b]\n', 'option = y\n']) configfile.close() config = Configuration(self.filename) self.assertEquals(('option', 'x'), iter(config.options('a')).next()) self.assertEquals(('option', 'y'), iter(config.options('b')).next()) self.assertRaises(StopIteration, iter(config.options('c')).next)
def getSettings(self, cls, store): if not isinstance(cls, basestring): mymodule = cls.__module__.lower() else: mymodule = cls.lower() # Do not add duplicates for object in store: if mymodule in object['module']: return mycount = len(mymodule.split('.')) prjconf = Configuration(conf.global_conf_path) rules = [(name.lower(), value.lower()) for name, value in prjconf.options('components')] rules.sort(lambda a, b:-cmp(len(a[0]), len(b[0]))) for pattern, value in rules: if pattern.startswith(mymodule + '.'): item = pattern.split(".") count = len(item) if count > mycount: header = item[mycount] if count > (mycount + 1): store.append({ 'module': mymodule, 'name': header + '.' + item[mycount + 1], 'default': self.parse_value(0, value), 'static': self.parse_boolean_value(1, value, True) })
def load_workflow_config_snippet(config, filename): """Loads the ticket-workflow section from the given file (expected to be in the 'workflows' tree) into the provided config. """ filename = resource_filename('trac.ticket', 'workflows/%s' % filename) new_config = Configuration(filename) for name, value in new_config.options('ticket-workflow'): config.set('ticket-workflow', name, value)
def load_workflow_config_snippet(config, filename): """Loads the ticket-workflow section from the given file (expected to be in the 'workflows' tree) into the provided config. """ filename = resource_filename('trac.ticket', 'workflows/%s' % filename) new_config = Configuration(filename) for name, value in new_config.options('ticket-workflow'): config.set('ticket-workflow', name, value)
def readconfig(filename): """Returns a list of raw config options""" config = Configuration(filename) rawactions = list(config.options('ticket-workflow')) debug("%s\n" % str(rawactions)) if not rawactions: sys.stderr.write("ERROR: You don't seem to have a [ticket-workflow] " "section.\n") sys.exit(1) return rawactions
def readconfig(filename): """Returns a list of raw config options""" config = Configuration(filename) rawactions = list(config.options('ticket-workflow')) debug("%s\n" % str(rawactions)) if not rawactions: sys.stderr.write("ERROR: You don't seem to have a [ticket-workflow] " "section.\n") sys.exit(1) return rawactions
def diff(file1, file2, ignored_sections=None, ignore_absent=False): """ :param file1: Filename :param file2: Filename :param list ignored_sections: List of ignored sections :param bool ignore_absent: Disables absent key reporting """ if ignored_sections is None: ignored_sections = [] if not os.path.exists(file1): raise ValueError('file %s does not exists' % file1) if not os.path.exists(file2): raise ValueError('file %s does not exists' % file2) conf1 = Configuration(file1) conf2 = Configuration(file2) fn1 = os.path.split(file1)[1] fn2 = os.path.split(file2)[1] conf1_sections = set(conf1.sections()) - set(ignored_sections) conf2_sections = set(conf2.sections()) - set(ignored_sections) for section in conf1.sections(): if section not in conf2_sections: print 'SECTION: %s not in %s' % (section, fn2) default = object() for section in conf1_sections: for key, value1 in conf1.options(section): if not conf2.has_option(section, key): if not ignore_absent: print '[%s] %s = %s is ABSENT from %s (but exists in %s)' % ( section, key, value1, fn2, fn1) else: value2 = conf2.get(section, key, default) if value2 != value1 and value2 is not default: print '[%s] %s = %s -> %s (%s -> %s)' % ( section, key, value1, value2, fn1, fn2)
def diff(file1, file2, ignored_sections=None, ignore_absent=False): """ :param file1: Filename :param file2: Filename :param list ignored_sections: List of ignored sections :param bool ignore_absent: Disables absent key reporting """ if ignored_sections is None: ignored_sections = [] if not os.path.exists(file1): raise ValueError("file %s does not exists" % file1) if not os.path.exists(file2): raise ValueError("file %s does not exists" % file2) conf1 = Configuration(file1) conf2 = Configuration(file2) fn1 = os.path.split(file1)[1] fn2 = os.path.split(file2)[1] conf1_sections = set(conf1.sections()) - set(ignored_sections) conf2_sections = set(conf2.sections()) - set(ignored_sections) for section in conf1.sections(): if section not in conf2_sections: print "SECTION: %s not in %s" % (section, fn2) default = object() for section in conf1_sections: for key, value1 in conf1.options(section): if not conf2.has_option(section, key): if not ignore_absent: print "[%s] %s = %s is ABSENT from %s (but exists in %s)" % (section, key, value1, fn2, fn1) else: value2 = conf2.get(section, key, default) if value2 != value1 and value2 is not default: print "[%s] %s = %s -> %s (%s -> %s)" % (section, key, value1, value2, fn1, fn2)
def getSettings(self, cls, store): if not isinstance(cls, basestring): mymodule = cls.__module__.lower() else: mymodule = cls.lower() # Do not add duplicates for object in store: if mymodule in object['module']: return mycount = len(mymodule.split('.')) prjconf = Configuration(conf.global_conf_path) rules = [(name.lower(), value.lower()) for name, value in prjconf.options('components')] rules.sort(lambda a, b: -cmp(len(a[0]), len(b[0]))) for pattern, value in rules: if pattern.startswith(mymodule + '.'): item = pattern.split(".") count = len(item) if count > mycount: header = item[mycount] if count > (mycount + 1): store.append({ 'module': mymodule, 'name': header + '.' + item[mycount + 1], 'default': self.parse_value(0, value), 'static': self.parse_boolean_value(1, value, True) })
def do_initenv(self, line): def initenv_error(msg): printerr(_("Initenv for '%(env)s' failed.", env=self.envname), "\n%s" % msg) if self.env_check(): initenv_error(_("Does an environment already exist?")) return 2 if os.path.exists(self.envname) and os.listdir(self.envname): initenv_error(_("Directory exists and is not empty.")) return 2 if not os.path.exists(os.path.dirname(self.envname)): initenv_error(_("Base directory '%(env)s' does not exist. Please " "create it manually and retry.", env=os.path.dirname(self.envname))) return 2 arg = self.arg_tokenize(line) inherit_paths = [] config_file_path = None i = 0 while i < len(arg): item = arg[i] if item.startswith('--inherit='): inherit_paths.append(arg.pop(i)[10:]) elif item.startswith('--config='): config_file_path = arg.pop(i)[9:] else: i += 1 config = None if config_file_path: if not os.path.exists(config_file_path): initenv_error(_("The file specified in the --config argument " "does not exist: %(path)s.", path=config_file_path)) return 2 try: config = Configuration(config_file_path) except TracError as e: initenv_error(e) return 2 arg = arg or [''] # Reset to usual empty in case we popped the only one project_name = None db_str = None repository_type = None repository_dir = None if len(arg) == 1 and not arg[0]: project_name, db_str = self.get_initenv_args() elif len(arg) == 2: project_name, db_str = arg elif len(arg) == 4: project_name, db_str, repository_type, repository_dir = arg else: initenv_error('Wrong number of arguments: %d' % len(arg)) return 2 try: printout(_("Creating and Initializing Project")) options = [] if config: for section in config.sections(defaults=False): options.extend((section, option, value) for option, value in config.options(section)) options.extend([ ('project', 'name', project_name), ('trac', 'database', db_str), ]) def add_nav_order_options(section, default): for i, name in enumerate(default, 1): options.append((section, name + '.order', float(i))) add_nav_order_options('mainnav', default_mainnav_order) add_nav_order_options('metanav', default_metanav_order) if repository_dir: options.extend([ ('repositories', '.type', repository_type), ('repositories', '.dir', repository_dir), ]) if inherit_paths: options.append(('inherit', 'file', ",\n ".join(inherit_paths))) try: self.__env = Environment(self.envname, create=True, options=options) except Exception as e: initenv_error(_('Failed to create environment.')) printerr(e) traceback.print_exc() sys.exit(1) # Add a few default wiki pages printout(_(" Installing default wiki pages")) pages_dir = pkg_resources.resource_filename('trac.wiki', 'default-pages') WikiAdmin(self.__env).load_pages(pages_dir) if repository_dir: try: repos = RepositoryManager(self.__env).get_repository('') if repos: printout(_(" Indexing default repository")) repos.sync(self._resync_feedback) except TracError as e: printerr(_(""" --------------------------------------------------------------------- Warning: couldn't index the default repository. This can happen for a variety of reasons: wrong repository type, no appropriate third party library for this repository type, no actual repository at the specified repository path... You can nevertheless start using your Trac environment, but you'll need to check again your trac.ini file and the [trac] repository_type and repository_path settings. """)) except Exception as e: initenv_error(to_unicode(e)) traceback.print_exc() return 2 printout(_(""" --------------------------------------------------------------------- Project environment for '%(project_name)s' created. You may now configure the environment by editing the file: %(config_path)s If you'd like to take this new project environment for a test drive, try running the Trac standalone web server `tracd`: tracd --port 8000 %(project_path)s Then point your browser to http://localhost:8000/%(project_dir)s. There you can also browse the documentation for your installed version of Trac, including information on further setup (such as deploying Trac to a real web server). The latest documentation can also always be found on the project website: http://trac.edgewall.org/ Congratulations! """, project_name=project_name, project_path=self.envname, project_dir=os.path.basename(self.envname), config_path=os.path.join(self.envname, 'conf', 'trac.ini')))
class MockEnvironment(Environment): """ An mock Environment object which does not need real environment. Useful for when needing real environment like access to loaded plugins etc but no environment is at hand. Looks like normal project by default but can be made to look like home project environment or hybrid of both. .. WARNING:: Be careful when using this! """ def __init__(self, config_file=None, enabled_plugins=None, path=None): """ :param str config_file: path to the main configuration file. Defaults to ``/etc/trac/project.ini`` which is normal project configuration. :param list enabled_plugins: An explicit list of plugins to load, instead of reading enabled [components] from ``config_file``. If empty list is given no plugins are loaded. However plugins can be still listed via ``extra_plugins`` arg. :param str path: path to the imaginary trac location. """ if config_file is None: # TODO: switch to some constant when can be done without conf from multiproject.core.configuration import conf config_file = conf.config_file # From Environment.setup_config: self.config = Configuration(config_file) if path is None: path = os.path.join( self.config.get('multiproject', 'sys_projects_root'), '__mock_environment__') if enabled_plugins is not None: # explicit list given, disable all from configuration for key, val in self.config.options('components'): self.config.remove('components', key) # and replace with the given list for plugin in enabled_plugins: self.config.set('components', plugin, u'enabled') # We override the Environment.__init__ here. # Environment.__init__ is as follows: # ComponentManager.__init__(self) # # self.path = path # self.systeminfo = [] # self._href = self._abs_href = None # # if create: # self.create(options) # else: # self.verify() # self.setup_config() # # if create: # for setup_participant in self.setup_participants: # setup_participant.environment_created() # The Environment.setup_config is as follows: # self.config = Configuration(os.path.join(self.path, 'conf', # 'trac.ini')) # self.setup_log() # from trac.loader import load_components # plugins_dir = self.shared_plugins_dir # load_components(self, plugins_dir and (plugins_dir,)) # We use suitable lines from these as follows: # From Environment.__init__: ComponentManager.__init__(self) self.path = path self.systeminfo = [] self._href = self._abs_href = None # Our own plugin hack ends here, and setup_config lines continue here self.setup_log() from trac.loader import load_components load_components(self)
def do_initenv(self, line): def initenv_error(msg): printerr(_("Initenv for '%(env)s' failed.", env=self.envname), "\n%s" % msg) if self.env_check(): initenv_error(_("Does an environment already exist?")) return 2 printout( _("Creating a new Trac environment at %(envname)s", envname=self.envname)) arg = self.arg_tokenize(line) inherit_paths = [] config_file_path = None i = 0 while i < len(arg): item = arg[i] if item.startswith('--inherit='): inherit_paths.append(arg.pop(i)[10:]) elif item.startswith('--config='): config_file_path = arg.pop(i)[9:] else: i += 1 config = None if config_file_path: if not os.path.exists(config_file_path): initenv_error( _( "The file specified in the --config argument " "does not exist: %(path)s.", path=config_file_path)) return 2 try: config = Configuration(config_file_path) except TracError as e: initenv_error(e) return 2 arg = arg or ['' ] # Reset to usual empty in case we popped the only one if len(arg) == 1 and not arg[0] and not config: project_name, db_str = self.get_initenv_args() elif len(arg) < 2 and config: project_name = db_str = None if arg[0]: project_name = arg[0] elif len(arg) == 2: project_name, db_str = arg else: initenv_error('Wrong number of arguments: %d' % len(arg)) return 2 options = [] if config: for section in config.sections(defaults=False): options.extend((section, option, value) for option, value in config.options(section)) if project_name is not None: options.append(('project', 'name', project_name)) if db_str is not None: options.append(('trac', 'database', db_str)) if inherit_paths: options.append( ('inherit', 'file', ",\n ".join(inherit_paths))) try: self.__env = Environment(self.envname, create=True, options=options) except TracError as e: initenv_error(e) return 2 except Exception as e: initenv_error(_('Failed to create environment.')) printerr(e) traceback.print_exc() sys.exit(1) printout( _(""" Project environment for '%(project_name)s' created. You may configure the environment by editing the file: %(config_path)s You can run the Trac standalone web server `tracd` and point your browser to http://localhost:8000/%(project_dir)s. tracd --port 8000 %(project_path)s Navigate to "Help/Guide" to browse the documentation for Trac, including information on further setup (such as deploying Trac to a real web server). The latest documentation can also be found on the project website: http://trac.edgewall.org/ """, project_name=project_name, project_path=self.envname, project_dir=os.path.basename(self.envname), config_path=self.__env.config_file_path))
def do_initenv(self, line): def initenv_error(msg): printerr(_("Initenv for '%(env)s' failed.", env=self.envname), "\n%s" % msg) if self.env_check(): initenv_error(_("Does an environment already exist?")) return 2 if os.path.exists(self.envname) and os.listdir(self.envname): initenv_error(_("Directory exists and is not empty.")) return 2 if not os.path.exists(os.path.dirname(self.envname)): initenv_error( _( "Base directory '%(env)s' does not exist. Please " "create it manually and retry.", env=os.path.dirname(self.envname))) return 2 arg = self.arg_tokenize(line) inherit_paths = [] config_file_path = None i = 0 while i < len(arg): item = arg[i] if item.startswith('--inherit='): inherit_paths.append(arg.pop(i)[10:]) elif item.startswith('--config='): config_file_path = arg.pop(i)[9:] else: i += 1 config = None if config_file_path: if not os.path.exists(config_file_path): initenv_error( _( "The file specified in the --config argument " "does not exist: %(path)s.", path=config_file_path)) return 2 try: config = Configuration(config_file_path) except TracError as e: initenv_error(e) return 2 arg = arg or ['' ] # Reset to usual empty in case we popped the only one project_name = None db_str = None repository_type = None repository_dir = None if len(arg) == 1 and not arg[0]: project_name, db_str = self.get_initenv_args() elif len(arg) == 2: project_name, db_str = arg elif len(arg) == 4: project_name, db_str, repository_type, repository_dir = arg else: initenv_error('Wrong number of arguments: %d' % len(arg)) return 2 try: printout(_("Creating and Initializing Project")) options = [] if config: for section in config.sections(defaults=False): options.extend( (section, option, value) for option, value in config.options(section)) options.extend([ ('project', 'name', project_name), ('trac', 'database', db_str), ]) def add_nav_order_options(section, default): for i, name in enumerate(default, 1): options.append((section, name + '.order', float(i))) add_nav_order_options('mainnav', default_mainnav_order) add_nav_order_options('metanav', default_metanav_order) if repository_dir: options.extend([ ('repositories', '.type', repository_type), ('repositories', '.dir', repository_dir), ]) if inherit_paths: options.append( ('inherit', 'file', ",\n ".join(inherit_paths))) try: self.__env = Environment(self.envname, create=True, options=options) except Exception as e: initenv_error(_('Failed to create environment.')) printerr(e) traceback.print_exc() sys.exit(1) # Add a few default wiki pages printout(_(" Installing default wiki pages")) pages_dir = pkg_resources.resource_filename( 'trac.wiki', 'default-pages') WikiAdmin(self.__env).load_pages(pages_dir) if repository_dir: try: repos = RepositoryManager(self.__env).get_repository('') if repos: printout(_(" Indexing default repository")) repos.sync(self._resync_feedback) except TracError as e: printerr( _(""" --------------------------------------------------------------------- Warning: couldn't index the default repository. This can happen for a variety of reasons: wrong repository type, no appropriate third party library for this repository type, no actual repository at the specified repository path... You can nevertheless start using your Trac environment, but you'll need to check again your trac.ini file and the [trac] repository_type and repository_path settings. """)) except Exception as e: initenv_error(to_unicode(e)) traceback.print_exc() return 2 printout( _(""" --------------------------------------------------------------------- Project environment for '%(project_name)s' created. You may now configure the environment by editing the file: %(config_path)s If you'd like to take this new project environment for a test drive, try running the Trac standalone web server `tracd`: tracd --port 8000 %(project_path)s Then point your browser to http://localhost:8000/%(project_dir)s. There you can also browse the documentation for your installed version of Trac, including information on further setup (such as deploying Trac to a real web server). The latest documentation can also always be found on the project website: http://trac.edgewall.org/ Congratulations! """, project_name=project_name, project_path=self.envname, project_dir=os.path.basename(self.envname), config_path=os.path.join(self.envname, 'conf', 'trac.ini')))
class MockEnvironment(Environment): """ An mock Environment object which does not need real environment. Useful for when needing real environment like access to loaded plugins etc but no environment is at hand. Looks like normal project by default but can be made to look like home project environment or hybrid of both. .. WARNING:: Be careful when using this! """ def __init__(self, config_file=None, enabled_plugins=None, path=None): """ :param str config_file: path to the main configuration file. Defaults to ``/etc/trac/project.ini`` which is normal project configuration. :param list enabled_plugins: An explicit list of plugins to load, instead of reading enabled [components] from ``config_file``. If empty list is given no plugins are loaded. However plugins can be still listed via ``extra_plugins`` arg. :param str path: path to the imaginary trac location. """ if config_file is None: # TODO: switch to some constant when can be done without conf from multiproject.core.configuration import conf config_file = conf.config_file # From Environment.setup_config: self.config = Configuration(config_file) if path is None: path = os.path.join(self.config.get('multiproject', 'sys_projects_root'), '__mock_environment__') if enabled_plugins is not None: # explicit list given, disable all from configuration for key, val in self.config.options('components'): self.config.remove('components', key) # and replace with the given list for plugin in enabled_plugins: self.config.set('components', plugin, u'enabled') # We override the Environment.__init__ here. # Environment.__init__ is as follows: # ComponentManager.__init__(self) # # self.path = path # self.systeminfo = [] # self._href = self._abs_href = None # # if create: # self.create(options) # else: # self.verify() # self.setup_config() # # if create: # for setup_participant in self.setup_participants: # setup_participant.environment_created() # The Environment.setup_config is as follows: # self.config = Configuration(os.path.join(self.path, 'conf', # 'trac.ini')) # self.setup_log() # from trac.loader import load_components # plugins_dir = self.shared_plugins_dir # load_components(self, plugins_dir and (plugins_dir,)) # We use suitable lines from these as follows: # From Environment.__init__: ComponentManager.__init__(self) self.path = path self.systeminfo = [] self._href = self._abs_href = None # Our own plugin hack ends here, and setup_config lines continue here self.setup_log() from trac.loader import load_components load_components(self)