Example #1
0
    def __init__(self, path, create=False, options=[]):
        """Initialize the Trac environment.
        
        @param path:   the absolute path to the Trac environment
        @param create: if `True`, the environment is created and populated with
                       default data; otherwise, the environment is expected to
                       already exist.
        @param options: A list of `(section, name, value)` tuples that define
                        configuration options
        """
        ComponentManager.__init__(self)

        self.path = path
        self.setup_config(load_defaults=create)
        self.setup_log()

        from trac.loader import load_components
        load_components(self)

        if create:
            self.create(options)
        else:
            self.verify()

        if create:
            for setup_participant in self.setup_participants:
                setup_participant.environment_created()
Example #2
0
def main():
    all_pages = sorted(
        name for name in resource_listdir('trac.wiki', 'default-pages')
        if not name.startswith('.'))
    args = parse_args(all_pages)
    if args.pages:
        pages = sorted(args.pages)
    else:
        pages = all_pages

    if args.download:
        download_default_pages(pages, args.prefix, args.strict)

    env = EnvironmentStub(disable=['trac.mimeview.pygments.*'])
    load_components(env)
    with env.db_transaction:
        for name in all_pages:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'),
               abs_href=Href('http://localhost/'),
               perm=MockPerm())
    for name in pages:
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource)
        out = DummyIO()
        DefaultWikiChecker(env, context, name).format(wiki.text, out)
Example #3
0
    def __init__(self, path, create=False, options=[]):
        """Initialize the Trac environment.
        
        @param path:   the absolute path to the Trac environment
        @param create: if `True`, the environment is created and populated with
                       default data; otherwise, the environment is expected to
                       already exist.
        @param options: A list of `(section, name, value)` tuples that define
                        configuration options
        """
        ComponentManager.__init__(self)

        self.path = path
        self.setup_config(load_defaults=create)
        self.setup_log()

        from trac.loader import load_components
        load_components(self)

        if create:
            self.create(options)
        else:
            self.verify()

        if create:
            for setup_participant in self.setup_participants:
                setup_participant.environment_created()
Example #4
0
File: env.py Project: pkdevbox/trac
 def setup_config(self):
     """Load the configuration file."""
     self.config = Configuration(self.config_file_path,
                                 {'envname': os.path.basename(self.path)})
     self.setup_log()
     plugins_dir = self.shared_plugins_dir
     load_components(self, plugins_dir and (plugins_dir,))
Example #5
0
def main():
    names = sorted(name for name in resource_listdir('trac.wiki',
                                                     'default-pages')
                        if not name.startswith('.'))

    env = EnvironmentStub()
    load_components(env)
    with env.db_transaction:
        for name in names:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'), abs_href=Href('http://trac.edgewall.org/'),
               perm=MockPerm(), chrome={})
    for name in sys.argv[1:]:
        name = os.path.basename(name)
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource, absurls=True)
        rst = wiki2rest(env, context, wiki)
        sys.stdout.write(rst)
Example #6
0
def main():
    options, args = parse_args()
    names = sorted(name
                   for name in resource_listdir('trac.wiki', 'default-pages')
                   if not name.startswith('.'))
    if args:
        args = sorted(set(names) & set(map(os.path.basename, args)))
    else:
        args = names

    if options.download:
        download_default_pages(args, options.prefix)

    env = EnvironmentStub()
    load_components(env)
    with env.db_transaction:
        for name in names:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'),
               abs_href=Href('http://localhost/'),
               perm=MockPerm())
    for name in args:
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource)
        out = DummyIO()
        DefaultWikiChecker(env, context, name).format(wiki.text, out)
Example #7
0
    def __init__(self, path, create=False, db_str=None):
        """Initialize the Trac environment.
        
        @param path:   the absolute path to the Trac environment
        @param create: if `True`, the environment is created and populated with
                       default data; otherwise, the environment is expected to
                       already exist.
        @param db_str: the database connection string
        """
        ComponentManager.__init__(self)

        try:  # Use binary I/O on Windows
            import msvcrt, sys
            msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
        except ImportError:
            pass

        self.path = path
        self.__cnx_pool = None
        if create:
            self.create(db_str)
        else:
            self.verify()
            self.load_config()
        self.setup_log()

        from trac.loader import load_components
        load_components(self)

        if create:
            for setup_participant in self.setup_participants:
                setup_participant.environment_created()
Example #8
0
def main():
    names = sorted(name
                   for name in resource_listdir('trac.wiki', 'default-pages')
                   if not name.startswith('.'))

    env = EnvironmentStub()
    load_components(env)
    with env.db_transaction:
        for name in names:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'),
               abs_href=Href('http://trac.edgewall.org/'),
               perm=MockPerm(),
               chrome={})
    for name in sys.argv[1:]:
        name = os.path.basename(name)
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource, absurls=True)
        rst = wiki2rest(env, context, wiki)
        sys.stdout.write(rst)
Example #9
0
    def __init__(self, path, create=False, db_str=None):
        """Initialize the Trac environment.
        
        @param path:   the absolute path to the Trac environment
        @param create: if `True`, the environment is created and populated with
                       default data; otherwise, the environment is expected to
                       already exist.
        @param db_str: the database connection string
        """
        ComponentManager.__init__(self)

        self.path = path
        self.__cnx_pool = None
        if create:
            self.create(db_str)
        else:
            self.verify()
            self.load_config()
        self.setup_log()

        from trac.loader import load_components
        load_components(self)

        if create:
            for setup_participant in self.setup_participants:
                setup_participant.environment_created()
Example #10
0
def main():
    options, args = parse_args()
    names = sorted(name for name in resource_listdir('trac.wiki',
                                                     'default-pages')
                        if not name.startswith('.'))
    if args:
        args = sorted(set(names) & set(map(os.path.basename, args)))
    else:
        args = names

    if options.download:
        download_default_pages(args, options.prefix)

    env = EnvironmentStub()
    load_components(env)
    with env.db_transaction:
        for name in names:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'), abs_href=Href('http://localhost/'),
               perm=MockPerm())
    for name in args:
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource)
        out = DummyIO()
        DefaultWikiChecker(env, context, name).format(wiki.text, out)
Example #11
0
 def setup_config(self):
     """Load the configuration file."""
     self.config = Configuration(self.config_file_path,
                                 {'envname': os.path.basename(self.path)})
     self.setup_log()
     plugins_dir = self.shared_plugins_dir
     load_components(self, plugins_dir and (plugins_dir,))
Example #12
0
 def setup_config(self):
     """Load the configuration file."""
     self.config = Configuration(os.path.join(self.path, 'conf', 'trac.ini'),
                                 {'envname': os.path.basename(self.path)})
     self.setup_log()
     from trac.loader import load_components
     plugins_dir = self.shared_plugins_dir
     load_components(self, plugins_dir and (plugins_dir,))
Example #13
0
 def setup_config(self):
     """Load the configuration file."""
     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, ))
Example #14
0
 def setup_config(self):
     """Load the configuration file."""
     self.config = Configuration(self.config_file_path,
                                 {'envname': self.name})
     if not self.config.exists:
         raise TracError(_("The configuration file is not found at "
                           "%(path)s", path=self.config_file_path))
     self.setup_log()
     plugins_dir = self.shared_plugins_dir
     load_components(self, plugins_dir and (plugins_dir,))
Example #15
0
    def restart(self):
        """Restarts the webserver"""
        self.stop()
        self.start()

        # Reload components e.g. those in /plugins folder
        from trac.loader import load_components

        global_env = self.get_trac_environment()
        plugins_dir = global_env.shared_plugins_dir
        load_components(global_env, plugins_dir and (plugins_dir,))
Example #16
0
    def restart(self):
        """Restarts the webserver"""
        self.stop()
        self.start()

        # Reload components e.g. those in /plugins folder
        from trac.loader import load_components

        global_env = self.get_trac_environment()
        plugins_dir = global_env.shared_plugins_dir
        load_components(global_env, plugins_dir and (plugins_dir, ))
Example #17
0
 def load_components(self, pkgs):
   r"""Load some packages to ensure that the components they 
   implement are available at testing time.
   """
   from trac.loader import load_components
   for pkg in pkgs :
     try :
       __import__(pkg)
     except ImportError :
       pass                        # Skip pkg. What a shame !
     else :
       mdl = sys.modules[pkg]
       load_components(self.env, dirname(dirname(mdl.__file__)))
Example #18
0
 def load_components(self, pkgs):
     r"""Load some packages to ensure that the components they 
 implement are available at testing time.
 """
     from trac.loader import load_components
     for pkg in pkgs:
         try:
             __import__(pkg)
         except ImportError:
             pass  # Skip pkg. What a shame !
         else:
             mdl = sys.modules[pkg]
             load_components(self.env, dirname(dirname(mdl.__file__)))
Example #19
0
    def __init__(self, path, create=False, options=[]):
        """Initialize the Trac environment.
        
        @param path:   the absolute path to the Trac environment
        @param create: if `True`, the environment is created and populated with
                       default data; otherwise, the environment is expected to
                       already exist.
        @param options: A list of `(section, name, value)` tuples that define
                        configuration options
        """
        ComponentManager.__init__(self)

        self.path = path
        self.setup_config(load_defaults=create)
        self.setup_log()

        from trac import core, __version__ as VERSION
        trac_version = get_pkginfo(core).get('version', VERSION)
        self.systeminfo = [
            ('Trac', trac_version),
            ('Python', sys.version),
            ('setuptools', setuptools.__version__),
            ]
        self.log.info('-' * 32 + ' environment startup [Trac %s] ' + '-' * 32,
                      trac_version)
        self._href = self._abs_href = None

        from trac.loader import load_components
        plugins_dir = self.shared_plugins_dir
        load_components(self, plugins_dir and (plugins_dir,))

        if create:
            self.create(options)
        else:
            self.verify()

        if create:
            for setup_participant in self.setup_participants:
                setup_participant.environment_created()

        self._known_users_cache_time = 0
        self._known_users_cache = None
Example #20
0
    def test_single_file_plugin_metadata(self):
        """Metadata is read from single-file plugins."""
        plugin_metadata = {
            'author': 'Trac Hacks',
            'author_email': '*****@*****.**',
            'home_page': 'https://trac-hacks.org/wiki/SingleFilePlugin',
            'license': 'BSD',
            'summary': 'The single-file plugin',
            'trac': 'https://my.trac.com',
        }
        plugin_content = """\
from trac.core import Component

author = '%(author)s'
author_email = '%(author_email)s'
home_page = '%(home_page)s'
license = '%(license)s'
summary = '%(summary)s'
trac = '%(trac)s'


class SingleFilePlugin(Component):
    pass
""" % plugin_metadata

        file_path = os.path.join(self.env.plugins_dir, 'single_file_plugin.py')
        os.mkdir(self.env.plugins_dir)
        create_file(file_path, plugin_content)
        load_components(self.env, (self.env.plugins_dir, ))

        req = MockRequest(self.env)
        panel = PluginAdminPanel(self.env)
        data = panel.render_admin_panel(req, 'general', 'plugin', None)[1]

        discovered_metadata = {}
        for item in data['plugins']:
            if item['name'] == 'single-file-plugin':
                discovered_metadata = item['info']

        for key, value in plugin_metadata.items():
            self.assertEqual(discovered_metadata[key], plugin_metadata[key])
Example #21
0
    def test_component_loaded_once(self):
        create_file(
            os.path.join(self.env.plugins_dir, 'RegressionTestRev6017.py'),
            """\
from trac.wiki.macros import WikiMacroBase

class RegressionTestRev6017Macro(WikiMacroBase):
    def expand_macro(self, formatter, name, content, args):
        return "Hello World"

""")

        loader.load_components(self.env)
        loader.load_components(self.env)

        loaded_components = [
            c for c in ComponentMeta._components
            if 'RegressionTestRev6017' in c.__name__
        ]

        self.assertEqual(1, len(loaded_components),
                         "Plugin loaded more than once.")
Example #22
0
    def test_entry_point_with_extras(self):
        """Load entry points with extras

        Entry points with absent dependencies should not be found in
        the component registry.
        """
        egg_file_src = self._build_egg_file('plugin1')
        egg_file_dst = os.path.join(self.env.plugins_dir,
                                    os.path.basename(egg_file_src))
        shutil.copyfile(egg_file_src, egg_file_dst)

        loader.load_components(self.env)
        from plugin1 import ComponentA, ComponentB
        self.components.append(ComponentA)
        self.components.append(ComponentB)

        from trac.env import IEnvironmentSetupParticipant
        registry = ComponentMeta._registry
        self.assertIn(ComponentA, ComponentMeta._components)
        self.assertIn(ComponentA, registry.get(IEnvironmentSetupParticipant))
        self.assertNotIn(ComponentB, ComponentMeta._components)
        self.assertNotIn(ComponentB,
                         registry.get(IEnvironmentSetupParticipant))
Example #23
0
    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)
Example #24
0
    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)