Example #1
0
 def test_node_in_hidden_default_repos(self):
     self.grant_perm('anonymous', 'BROWSER_VIEW', 'FILE_VIEW')
     provider = DbRepositoryProvider(self.env)
     provider.modify_repository('(default)', {'hidden': 'enabled'})
     req = self.create_request(path_info='/browser/blah-blah-file')
     template, data, content_type = self.process_request(req)
     self.assertEqual('', data['reponame'])
     self.assertEqual('blah-blah-file', data['path'])
Example #2
0
 def test_no_viewable_repositories_without_browser_view(self):
     provider = DbRepositoryProvider(self.env)
     provider.remove_repository('allow')
     req = self.create_request(path_info='/browser/')
     try:
         self.process_request(req)
         self.fail('PermissionError not raised')
     except PermissionError, e:
         self.assertEqual('BROWSER_VIEW', e.action)
         self.assertEqual(None, e.resource)
Example #3
0
 def setUp(self):
     super(BrowserModulePermissionsTestCase, self).setUp(BrowserModule)
     provider = DbRepositoryProvider(self.env)
     provider.add_repository('(default)', '/', 'mock')
     provider.add_repository('allow', '/', 'mock')
     provider.add_repository('deny', '/', 'mock')
     provider.add_repository('raise', '/', 'mock')
Example #4
0
 def test_repository_index_with_hidden_default_repos(self):
     self.grant_perm('anonymous', 'BROWSER_VIEW', 'FILE_VIEW')
     provider = DbRepositoryProvider(self.env)
     provider.modify_repository('(default)', {'hidden': 'enabled'})
     req = self.create_request(path_info='/browser/')
     template, data, content_type = self.process_request(req)
     self.assertEqual(None, data['repos'])
     repo_data = data['repo']  # for repository index
     self.assertEqual('allow', repo_data['repositories'][0][0])
     self.assertEqual('raise', repo_data['repositories'][1][0])
     self.assertEqual(2, len(repo_data['repositories']))
Example #5
0
 def test_repository_index_with_hidden_default_repos(self):
     self.grant_perm('anonymous', 'BROWSER_VIEW', 'FILE_VIEW')
     provider = DbRepositoryProvider(self.env)
     provider.modify_repository('(default)', {'hidden': 'enabled'})
     req = MockRequest(self.env,
                       authname='anonymous',
                       path_info='/browser/')
     template, data = self.process_request(req)
     self.assertIsNone(data['repos'])
     repo_data = data['repo']  # for repository index
     self.assertEqual('allow', repo_data['repositories'][0][0])
     self.assertEqual('raise', repo_data['repositories'][1][0])
     self.assertEqual(2, len(repo_data['repositories']))
Example #6
0
    def test_repository_providers_disabled(self):
        """Repository configuration is rewritten when repository providers
        are disabled.
        """
        projects_list = os.path.join(self.env.path, 'projects_list')
        projects_base = os.path.dirname(projects_list)
        projects_url = 'http://localhost/%s'
        with open(projects_list, 'w') as f:
            f.write("""
            repos1 user1+<*****@*****.**>
            repos2
            """)
        config = self.env.config['git']
        config.set('projects_list', projects_list)
        config.set('projects_base', projects_base)
        config.set('projects_url', projects_url)
        db_provider = DbRepositoryProvider(self.env)
        db_provider.add_repository('repos3', '/var/git/repos3', 'git')
        db_provider.add_repository('repos4', '/var/git/repos4', 'git')
        config = self.env.config['repositories']
        config.set('repos5.dir', '/var/svn/repos4')
        config.set('repos5.type', 'svn')
        config.set('repos6.dir', '/var/svn/repos5')
        config.set('repos6.type', 'svn')
        self.env.disable_component(GitwebProjectsRepositoryProvider)
        self.env.disable_component(DbRepositoryProvider)
        self.env.disable_component(RepositoryManager)

        db32.do_upgrade(self.env, VERSION, None)

        self.env.enable_component(GitwebProjectsRepositoryProvider)
        self.env.enable_component(DbRepositoryProvider)
        self.env.enable_component(RepositoryManager)
        repos = RepositoryManager(self.env).get_all_repositories()
        config = self.env.config['gitweb-repositories']
        self.assertEqual(projects_list, config.get('projects_list'))
        self.assertEqual(projects_base, config.get('projects_base'))
        self.assertEqual(projects_url, config.get('projects_url'))
        self.assertEqual('repos1', config.get('sync_per_request'))
        self.assertIn('repos1', repos)
        self.assertTrue(repos['repos1']['sync_per_request'])
        self.assertIn('repos2', repos)
        self.assertFalse(repos['repos2']['sync_per_request'])
        self.assertIn('repos3', repos)
        self.assertTrue(repos['repos3']['sync_per_request'])
        self.assertIn('repos4', repos)
        self.assertFalse(repos['repos4']['sync_per_request'])
        self.assertIn('repos5', repos)
        self.assertTrue(repos['repos5']['sync_per_request'])
        self.assertIn('repos6', repos)
        self.assertFalse(repos['repos6']['sync_per_request'])
Example #7
0
 def test_render_admin_with_alias_to_default_repos(self):
     db_provider = DbRepositoryProvider(self.env)
     db_provider.add_alias('', '')
     db_provider.add_alias('blah', '')
     panel = RepositoryAdminPanel(self.env)
     req = Mock(method='GET', chrome={}, args={}, session={},
                abs_href=Href('/'), href=Href('/'), locale=None,
                perm=MockPerm(), authname='anonymous', tz=utc)
     template, data = panel.render_admin_panel(req, 'versioncontrol',
                                               'repository', '')
     repositories = data['repositories']
     self.assertEqual('', repositories['']['name'])
     self.assertEqual('', repositories['']['alias'])
     self.assertEqual('blah', repositories['blah']['name'])
     self.assertEqual('', repositories['blah']['alias'])
Example #8
0
    def test_no_viewable_repositories_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)

        provider.remove_repository('allow')
        provider.remove_repository('(default)')
        provider.remove_repository('raise')

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No viewable repositories', str(e))
        req = MockRequest(self.env, path_info='/browser/allow/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No node allow', str(e))
        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/deny/')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError as e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual('source', e.resource.realm)
            self.assertEqual('/', e.resource.id)
            self.assertEqual('repository', e.resource.parent.realm)
            self.assertEqual('deny', e.resource.parent.id)

        provider.remove_repository('deny')
        req = MockRequest(self.env, path_info='/browser/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No viewable repositories', str(e))
        req = MockRequest(self.env, path_info='/browser/deny/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No node deny', str(e))
Example #9
0
def do_upgrade(env, version, cursor):
    """Replace list of repositories in [trac] repository_sync_per_request
    with boolean values [repositories] <repos>.sync_per_request and a list
    of repositories in [gitweb-repositories] sync_per_request. Move and
    rename the Gitweb configuration options from the [git] section to
    the [gitweb-repositories] section.
    """
    backup_config_file(env, '.db32.bak')
    repos_sync_per_request = \
        env.config.getlist('trac', 'repository_sync_per_request', '(default)')

    for suffix in ('base', 'list', 'url'):
        option_name = 'projects_' + suffix
        env.config.set('gitweb-repositories', option_name,
                       env.config.get('git', option_name))
        env.config.remove('git', option_name)
        env.log.info("Moved [git] %s -> [gitweb-repositories] %s", option_name,
                     option_name)

    rm = RepositoryManager(env)
    if repos_sync_per_request:
        for name, _ in rm.get_repositories():
            sync_per_request = (name or '(default)') in repos_sync_per_request
            if sync_per_request:
                env.config.set('repositories', name + '.sync_per_request',
                               'true')
                env.log.info("Enabled sync_per_request for %s", name)

        gwrp = GitwebProjectsRepositoryProvider(env)
        gitweb_repo_names = [name for name, _ in gwrp.get_repositories()]
        sync_per_request = \
            ', '.join(set(gitweb_repo_names) & set(repos_sync_per_request))
        env.config.set('gitweb-repositories', 'sync_per_request',
                       sync_per_request)
        env.log.info("Enabled sync_per_request for %s", sync_per_request)

        db_provider = DbRepositoryProvider(env)
        for name, _ in db_provider.get_repositories():
            sync_per_request = (name or '(default)') in repos_sync_per_request
            changes = {'sync_per_request': sync_per_request}
            db_provider.modify_repository(name, changes)
            if sync_per_request:
                env.log.info("Enabled sync_per_request for %s", name)

    env.config.remove('trac', 'repository_sync_per_request')
    env.log.info("Removed [trac] repository_sync_per_request option")
    env.config.save()
    rm.reload_repositories()
Example #10
0
    def test_repository_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')

        req = self.create_request(path_info='/browser/')
        rv = self.process_request(req)
        self.assertEqual('', rv[1]['repos'].name)

        req = self.create_request(path_info='/browser/allow')
        rv = self.process_request(req)
        self.assertEqual('allow', rv[1]['repos'].name)

        req = self.create_request(path_info='/browser/deny')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError as e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual('source', e.resource.realm)
            self.assertEqual('/', e.resource.id)
            self.assertEqual('repository', e.resource.parent.realm)
            self.assertEqual('deny', e.resource.parent.id)

        DbRepositoryProvider(self.env).remove_repository('(default)')
        req = self.create_request(path_info='/browser/')
        rv = self.process_request(req)
        self.assertEqual(None, rv[1]['repos'])

        req = self.create_request(path_info='/browser/blah-blah-file')
        self.assertRaises(ResourceNotFound, self.process_request, req)
Example #11
0
File: svn_fs.py Project: t2y/trac
 def test_canonical_repos_path(self):
     # Assertion `svn_dirent_is_canonical` with leading double slashes
     # in repository path if os.name == 'posix' (#10390)
     DbRepositoryProvider(self.env).add_repository(
         'canonical-path', '//' + REPOS_PATH.lstrip('/'), 'direct-svnfs')
     repos = self.env.get_repository('canonical-path')
     self.assertEqual(REPOS_PATH, repos.path)
Example #12
0
    def test_repository_without_browser_view(self):
        req = self.create_request(path_info='/browser/')
        rv = self.process_request(req)
        # cannot view default repository but don't raise PermissionError
        self.assertEqual(None, rv[1]['repos'])

        req = self.create_request(path_info='/browser/allow')
        rv = self.process_request(req)
        self.assertEqual('allow', rv[1]['repos'].name)

        req = self.create_request(path_info='/browser/deny')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError as e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual('source', e.resource.realm)
            self.assertEqual('/', e.resource.id)
            self.assertEqual('repository', e.resource.parent.realm)
            self.assertEqual('deny', e.resource.parent.id)

        DbRepositoryProvider(self.env).remove_repository('(default)')
        req = self.create_request(path_info='/browser/')
        rv = self.process_request(req)
        self.assertEqual(None, rv[1]['repos'])

        req = self.create_request(path_info='/browser/blah-blah-file')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError as e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual(None, e.resource)
Example #13
0
 def setUp(self):
     self.env = EnvironmentStub(enable=['trac.*', FullTextSearch])
     DbRepositoryProvider(self.env).add_repository('', self.repos_path,
                                                   'svn')
     self.repos = self.env.get_repository('')
     self.repos.sync()
     self.fts = FullTextSearch(self.env)
     self.fts.backend = Backend(self.fts.solr_endpoint, self.env.log,
                                MockSolrInterface)
Example #14
0
    def test_no_viewable_repositories_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)

        provider.remove_repository('allow')
        provider.remove_repository('(default)')
        provider.remove_repository('raise')
        req = self.create_request(path_info='/browser/')
        self.assertRaises(ResourceNotFound, self.process_request, req)
        req = self.create_request(path_info='/browser/allow/')
        self.assertRaises(ResourceNotFound, self.process_request, req)
        req = self.create_request(path_info='/browser/raise')
        self.assertRaises(ResourceNotFound, self.process_request, req)
        req = self.create_request(path_info='/browser/deny/')
        self.assertRaises(PermissionError, self.process_request, req)

        provider.remove_repository('deny')
        req = self.create_request(path_info='/browser/deny/')
        self.assertRaises(ResourceNotFound, self.process_request, req)
Example #15
0
File: svn_fs.py Project: t2y/trac
 def test_get_annotations_lower_drive_letter(self):
     # If the drive letter in the uri is lower case on Windows, a
     # SubversionException raises (#10514).
     drive, tail = os.path.splitdrive(REPOS_PATH)
     repos_path = drive.lower() + tail
     DbRepositoryProvider(self.env).add_repository('lowercase', repos_path,
                                                   'direct-svnfs')
     repos = self.env.get_repository('lowercase')
     node = repos.get_node(u'/tête/R\xe9sum\xe9.txt', 25)
     self.assertEqual([23, 23, 23, 25, 24, 23, 23, 23, 23, 23, 24, 23, 20],
                      node.get_annotations())
Example #16
0
    def test_get_navigation_items_without_browser_view(self):
        provider = DbRepositoryProvider(self.env)
        req = MockRequest(self.env, path_info='/')
        self.assertEqual('browser', next(self.get_navigation_items(req))[1])

        provider.remove_repository('(default)')
        self.assertEqual('browser', next(self.get_navigation_items(req))[1])

        provider.remove_repository('deny')
        self.assertEqual('browser', next(self.get_navigation_items(req))[1])

        provider.remove_repository('allow')
        self.assertEqual([], list(self.get_navigation_items(req)))
Example #17
0
File: svn_fs.py Project: t2y/trac
 def setUp(self):
     self.env = EnvironmentStub()
     repositories = self.env.config['repositories']
     dbprovider = DbRepositoryProvider(self.env)
     dbprovider.add_repository(REPOS_NAME, self.path, 'direct-svnfs')
     dbprovider.modify_repository(REPOS_NAME, {'url': URL})
     self.repos = self.env.get_repository(REPOS_NAME)
Example #18
0
File: svn_fs.py Project: t2y/trac
 def setUp(self):
     self.env = EnvironmentStub()
     dbprovider = DbRepositoryProvider(self.env)
     dbprovider.add_repository(REPOS_NAME, self.path, 'svn')
     dbprovider.modify_repository(REPOS_NAME, {'url': URL})
     self.repos = self.env.get_repository(REPOS_NAME)
     self.repos.sync()
Example #19
0
    def test_get_navigation_items_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)
        req = MockRequest(self.env, path_info='/')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('allow')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('deny')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('(default)')
        self.assertEqual([], list(self.get_navigation_items(req)))
    def get_admin_commands(self):
        yield ('repository create', '<repos> <type> <owner> [dir]',
               "Create a new managed repository", self._complete_create,
               self._do_create)
        yield ('repository fork', '<repos> <type> [dir]',
               "Fork an existing managed repository", self._complete_create,
               self._do_fork)
        yield ('repository remove_managed', '<repos> <delete from disk>',
               """Remove a managed repository

               Using the built-in command `repository remove' on a
               managed repository might leave unusable entries in the db
               and will not delete the repository from the file system.

               If <delete from disk> is 'true', contents are also removed
               permanently from disk.
               """, self._complete_remove_managed, self._do_remove_managed)
        attrs = set(DbRepositoryProvider(self.env).repository_attrs)
        yield ('repository set_managed', '<repos> <key> <value>',
               """Set an attribute of a managed repository

               Using the built-in command `repository set' on a managed
               repository might corrupt the db.

               The following keys are supported: %s
               """ % ", ".join(attrs - set(['type'])),
               self._complete_set_managed, self._do_set)
        yield ('repository list_managed', '', "List only managed repositories",
               None, self._do_list_managed)
        yield ('repository list_unmanaged', None,
               "List only unmanaged repositories", None,
               self._do_list_unmanaged)
        yield ('role add', '<repos> <role> <user> [user] [...]',
               """Add a new role

               The following roles are supported: %s
               """ % ", ".join(RepositoryManager(self.env).roles),
               self._complete_role_add, self._do_role_add)
        yield ('role remove', '<repos> <role> <user> [user] [...]',
               "Remove an existing role", self._complete_role_remove,
               self._do_role_remove)
        yield ('role export', '[file]',
               "Export repository roles to a file or stdout as CSV", None,
               self._do_role_export)
        yield ('role import', '[file]',
               "Import repository roles from a file or stdin as CSV",
               self._complete_role_import, self._do_role_import)
        yield ('role list', '<repos>', "List roles for given repository",
               self._complete_role_list, self._do_role_list)
        yield ('write_auth_files', '',
               "Rewrites all configured auth files for all managed"
               "repositories", None, self._do_write_auth_files)
Example #21
0
    def test_no_viewable_repositories_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)

        provider.remove_repository('allow')
        provider.remove_repository('(default)')
        provider.remove_repository('raise')

        req = self.create_request(path_info='/browser/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No viewable repositories', unicode(e))
        req = self.create_request(path_info='/browser/allow/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No node allow', unicode(e))
        req = self.create_request(path_info='/browser/deny/')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError as e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual('source', e.resource.realm)
            self.assertEqual('/', e.resource.id)
            self.assertEqual('repository', e.resource.parent.realm)
            self.assertEqual('deny', e.resource.parent.id)

        provider.remove_repository('deny')
        req = self.create_request(path_info='/browser/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No viewable repositories', unicode(e))
        req = self.create_request(path_info='/browser/deny/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound as e:
            self.assertEqual('No node deny', unicode(e))
Example #22
0
    def register_repository(self, repository, name=None):
        """Register a repository with trac"""

        project = repository.project
        tracname = name if name is not None else repository.name

        if repository.name in project.data.get('plugins',
                                               {}).get('trac', {}).get(
                                                   repository.type, {}):
            logger.error(
                "Repository %s:%s is already registered in project %s",
                repository.type, repository.name, project.name)
            return False

        if repository.type not in self.typemap:
            logger.error("Repository type %s is not supported in Trac",
                         repository.type)
            return False

        if not self.has_env(project):
            logger.warning(
                "Tried to add repository %s:%s to Trac of project %s, but there is no environment",
                repository.type, repository.name, project.name)
            return False

        try:
            env = Environment(self.get_env_path(project))

            DbRepositoryProvider(env).add_repository(
                tracname, repository.path, self.typemap[repository.type])

            # save mapping in project
            project.data.setdefault('plugins',
                                    {}).setdefault('trac', {}).setdefault(
                                        repository.type,
                                        {})[repository.name] = tracname
            project.save()

            # Synchronise repository
            rm = RepositoryManager(env)
            repos = rm.get_repository(tracname)
            repos.sync(lambda rev: logger.debug("Synced revision: %s", rev),
                       clean=True)

            return True
        except Exception as e:
            logger.exception(
                "Exception occured while addingrepository %s:%s to Trac of project %s",
                repository.type, repository.name, project.name)
            return False
Example #23
0
    def test_no_viewable_repositories_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)

        provider.remove_repository('allow')
        provider.remove_repository('(default)')
        provider.remove_repository('raise')

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound, e:
            self.assertEqual('No viewable repositories', unicode(e))
Example #24
0
    def test_get_navigation_items_without_browser_view(self):
        provider = DbRepositoryProvider(self.env)
        req = self.create_request(path_info='/')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('(default)')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('deny')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('allow')
        self.assertEqual([], list(self.get_navigation_items(req)))
Example #25
0
File: svn_fs.py Project: t2y/trac
class SubversionConnectorTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub()
        self.repos_path = tempfile.mkdtemp(prefix='trac-svnrepos-')
        self.dbprovider = DbRepositoryProvider(self.env)
        pool = core.svn_pool_create(None)
        repos.svn_repos_create(self.repos_path, '', '', None, None, pool)
        self.dbprovider.add_repository(REPOS_NAME, self.repos_path, 'svn')

    def tearDown(self):
        self.env.reset_db()
        # clear cached repositories to avoid TypeError on termination (#11505)
        RepositoryManager(self.env).reload_repositories()

    def _svn_version_from_system_info(self):
        svn_version = None
        for name, version in self.env.get_systeminfo():
            if name == 'Subversion':
                svn_version = version
        return svn_version

    def test_get_system_info_repository_not_initialized(self):
        # SubversionConnector is not a required component when there are no
        # Subversion repositories configured, and the Subversion version is
        # not returned in system info.
        self.assertFalse(svn_fs.SubversionConnector(self.env).required)
        self.assertIsNone(self._svn_version_from_system_info())

    def test_get_system_info_repository_initialized(self):
        # SubversionConnector is a required component when there are
        # Subversion repositories configured, and the Subversion version is
        # returned in system info.
        RepositoryManager(self.env).get_repository(REPOS_NAME)

        self.assertTrue(svn_fs.SubversionConnector(self.env).required)
        self.assertIsNotNone(self._svn_version_from_system_info())
Example #26
0
    def pre_delete_repository(self, repository):
        tracrepo = repository.project.data.get('plugins', {}).get(
            'trac', {}).get(repository.type, {}).get(repository.name)
        if tracrepo and self.has_env(repository.project):
            # remove it
            logger.info("Removing repository %s from Trac environment %s",
                        tracrepo, repository.project.name)
            env = Environment(self.get_env_path(repository.project))
            DbRepositoryProvider(env).remove_repository(tracrepo)

            # clean up
            del repository.project.data['plugins']['trac'][repository.type][
                repository.name]
            if not repository.project.data['plugins']['trac'][repository.type]:
                del repository.project.data['plugins']['trac'][repository.type]
Example #27
0
    def unregister_repository(self, repository):
        tracrepo = self.get_tracname_of_repository(repository)
        if tracrepo is not None and self.has_env(repository.project):
            # remove it
            logger.info("Removing repository %s from Trac environment %s",
                        tracrepo, repository.project.name)
            env = Environment(self.get_env_path(repository.project))
            DbRepositoryProvider(env).remove_repository(tracrepo)

            # clean up
            del repository.project.data['plugins']['trac'][repository.type][
                repository.name]
            if not repository.project.data['plugins']['trac'][repository.type]:
                del repository.project.data['plugins']['trac'][repository.type]

            repository.project.save()
Example #28
0
    def test_no_viewable_repositories_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)

        provider.remove_repository('allow')
        provider.remove_repository('(default)')
        provider.remove_repository('raise')

        req = self.create_request(path_info='/browser/')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound, e:
            self.assertEqual('No viewable repositories', unicode(e))
Example #29
0
 def test_no_viewable_repositories_without_browser_view(self):
     provider = DbRepositoryProvider(self.env)
     provider.remove_repository('allow')
     req = self.create_request(path_info='/browser/')
     try:
         self.process_request(req)
         self.fail('PermissionError not raised')
     except PermissionError as e:
         self.assertEqual('BROWSER_VIEW', e.action)
         self.assertEqual(None, e.resource)
     provider.remove_repository('deny')
     provider.remove_repository('(default)')
     req = self.create_request(path_info='/browser/')
     try:
         self.process_request(req)
         self.fail('PermissionError not raised')
     except PermissionError as e:
         self.assertEqual('BROWSER_VIEW', e.action)
         self.assertEqual(None, e.resource)
Example #30
0
    def test_rev_is_anchestor_of(self):
        # regression test for #11215
        path = os.path.join(self.repos_path, '.git')
        DbRepositoryProvider(self.env).add_repository('gitrepos', path, 'git')
        repos = self.env.get_repository('gitrepos')
        parent_rev = repos.youngest_rev

        create_file(os.path.join(self.repos_path, 'ticket11215.txt'))
        self._git('add', 'ticket11215.txt')
        self._git_commit('-m', 'ticket11215',
                         date=datetime(2013, 6, 27, 18, 26, 2))
        repos.sync()
        rev = repos.youngest_rev

        self.assertNotEqual(rev, parent_rev)
        self.assertFalse(repos.rev_older_than(None, None))
        self.assertFalse(repos.rev_older_than(None, rev[:7]))
        self.assertFalse(repos.rev_older_than(rev[:7], None))
        self.assertTrue(repos.rev_older_than(parent_rev, rev))
        self.assertTrue(repos.rev_older_than(parent_rev[:7], rev[:7]))
        self.assertFalse(repos.rev_older_than(rev, parent_rev))
        self.assertFalse(repos.rev_older_than(rev[:7], parent_rev[:7]))
Example #31
0
    def test_node_get_history_with_empty_commit(self):
        # regression test for #11328
        path = os.path.join(self.repos_path, '.git')
        DbRepositoryProvider(self.env).add_repository('gitrepos', path, 'git')
        repos = self.env.get_repository('gitrepos')
        parent_rev = repos.youngest_rev

        self._git_commit('-m', 'ticket:11328', '--allow-empty',
                         date=datetime(2013, 10, 15, 9, 46, 27))
        repos.sync()
        rev = repos.youngest_rev

        node = repos.get_node('', rev)
        self.assertEqual(rev, repos.git.last_change(rev, ''))
        history = list(node.get_history())
        self.assertEqual(u'', history[0][0])
        self.assertEqual(rev, history[0][1])
        self.assertEqual(Changeset.EDIT, history[0][2])
        self.assertEqual(u'', history[1][0])
        self.assertEqual(parent_rev, history[1][1])
        self.assertEqual(Changeset.ADD, history[1][2])
        self.assertEqual(2, len(history))
Example #32
0
 def test_render_admin_with_alias_to_default_repos(self):
     db_provider = DbRepositoryProvider(self.env)
     db_provider.add_alias('', '')
     db_provider.add_alias('blah', '')
     panel = RepositoryAdminPanel(self.env)
     req = Mock(method='GET',
                chrome={},
                args={},
                session={},
                abs_href=Href('/'),
                href=Href('/'),
                locale=None,
                perm=MockPerm(),
                authname='anonymous',
                tz=utc)
     template, data = panel.render_admin_panel(req, 'versioncontrol',
                                               'repository', '')
     repositories = data['repositories']
     self.assertEqual('', repositories['']['name'])
     self.assertEqual('', repositories['']['alias'])
     self.assertEqual('blah', repositories['blah']['name'])
     self.assertEqual('', repositories['blah']['alias'])
Example #33
0
        self.assertEqual('allow', rv[1]['repos'].name)

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/deny')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError, e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual('source', e.resource.realm)
            self.assertEqual('/', e.resource.id)
            self.assertEqual('repository', e.resource.parent.realm)
            self.assertEqual('deny', e.resource.parent.id)

        DbRepositoryProvider(self.env).remove_repository('(default)')
        req = MockRequest(self.env, path_info='/browser/')
        rv = self.process_request(req)
        self.assertEqual(None, rv[1]['repos'])

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/blah-blah-file')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError, e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual(None, e.resource)

    def test_node_with_file_view(self):
Example #34
0
File: api.py Project: pkdevbox/trac
class DbRepositoryProviderTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub()
        self.db_provider = DbRepositoryProvider(self.env)

    def tearDown(self):
        self.env.reset_db()

    def verify_raises(self, exc, message, func, *args, **kwargs):
        try:
            func(*args, **kwargs)
            self.fail('%s not raised' % exc.__name__)
        except exc as e:
            self.assertEqual(message, unicode(e))

    def do_remove(self, reponame, message):
        self.verify_raises(TracError, message,
                           self.db_provider.remove_repository, reponame)

    def do_modify(self, reponame, changes, message):
        self.verify_raises(TracError, message,
                           self.db_provider.modify_repository, reponame,
                           changes)

    def do_alias(self, reponame, target, message):
        self.verify_raises(TracError, message, self.db_provider.add_alias,
                           reponame, target)

    def test_add_alias(self):
        self.db_provider.add_repository('', '/path/to/repos')
        self.db_provider.add_repository('target', '/path/to/repos')
        self.db_provider.add_alias('blah1', '')
        self.db_provider.add_alias('blah2', '(default)')
        self.db_provider.add_alias('blah3', 'target')
        repositories = RepositoryManager(self.env).get_all_repositories()
        self.assertEqual(['', 'blah1', 'blah2', 'blah3', 'target'],
                         sorted(repositories))
        self.assertEqual('', repositories['blah1']['alias'])
        self.assertEqual('', repositories['blah2']['alias'])
        self.assertEqual('target', repositories['blah3']['alias'])

    def test_add_alias_to_non_existent_repository(self):
        self.do_alias('', '',
                      'Repository "(default)" doesn\'t exist')
        self.do_alias('', '(default)',
                      'Repository "(default)" doesn\'t exist')
        self.do_alias('blah', '',
                      'Repository "(default)" doesn\'t exist')
        self.do_alias('blah', '(default)',
                      'Repository "(default)" doesn\'t exist')
        self.do_alias('blah', 'blah', 'Repository "blah" doesn\'t exist')
        self.do_alias('', 'blah', 'Repository "blah" doesn\'t exist')
        self.do_alias('(default)', 'blah', 'Repository "blah" doesn\'t exist')

    def test_add_alias_to_repository_in_tracini(self):
        config = self.env.config
        config.set('repositories', '.dir', '/path/to/repos')
        config.set('repositories', '.type', '')
        config.set('repositories', 'target.dir', '/path/to/repos')
        config.set('repositories', 'target.type', '')
        config.set('repositories', 'alias-default.alias', '')
        config.set('repositories', 'alias-target.alias', 'target')
        self.db_provider.add_alias('blah1', '')
        self.db_provider.add_alias('blah2', 'target')
        self.assertRaises(TracError, self.db_provider.add_alias, 'blah3',
                          'notfound')
        repositories = RepositoryManager(self.env).get_all_repositories()
        self.assertEqual(['', 'alias-default', 'alias-target', 'blah1',
                          'blah2', 'target'], sorted(repositories))
        self.assertEqual('', repositories['blah1']['alias'])
        self.assertEqual('target', repositories['blah2']['alias'])

    def test_add_alias_to_alias(self):
        config = self.env.config
        config.set('repositories', 'target.dir', '/path/to/repos')
        config.set('repositories', 'target.type', '')
        config.set('repositories', '.alias', 'target')
        config.set('repositories', 'alias.alias', 'target')
        self.do_alias('blah', '',
                      'Cannot create an alias to the alias "(default)"')
        self.do_alias('blah', '(default)',
                      'Cannot create an alias to the alias "(default)"')
        self.do_alias('blah', 'alias',
                      'Cannot create an alias to the alias "alias"')

    def test_remove_repository_used_in_aliases(self):
        self.db_provider.add_repository('', '/path/to/repos')
        self.db_provider.add_repository('blah', '/path/to/repos')
        self.db_provider.add_alias('alias-blah', 'blah')
        self.db_provider.add_alias('alias-default', '')
        self.do_remove('', 'Cannot remove the repository "(default)" used in '
                           'aliases')
        self.do_remove('(default)', 'Cannot remove the repository "(default)" '
                                    'used in aliases')
        self.do_remove('blah', 'Cannot remove the repository "blah" used in '
                               'aliases')

    def test_modify_repository_used_in_aliases(self):
        self.db_provider.add_repository('', '/path/to/repos')
        self.db_provider.add_repository('blah', '/path/to/repos')
        self.db_provider.add_alias('alias-blah', 'blah')
        self.db_provider.add_alias('alias-default', '')
        self.do_modify('', {'name': 'new-name'},
                       'Cannot rename the repository "(default)" used in '
                       'aliases')
        self.do_modify('(default)', {'name': 'new-name'},
                       'Cannot rename the repository "(default)" used in '
                       'aliases')
        self.do_modify('blah', {'name': 'new-name'},
                       'Cannot rename the repository "blah" used in aliases')
        self.db_provider.modify_repository('', {'dir': '/path/to/new-path'})
Example #35
0
File: api.py Project: pkdevbox/trac
 def setUp(self):
     self.env = EnvironmentStub()
     self.db_provider = DbRepositoryProvider(self.env)
Example #36
0
 def setUp(self):
     self._super = super(LogModuleTestCase, self)
     self._super.setUp(LogModule)
     provider = DbRepositoryProvider(self.env)
     provider.add_repository('mock', '/', mock_repotype)
 def _complete_set_managed(self, args):
     if len(args) == 1:
         return self._complete_managed_repositories(args)
     elif len(args) == 2:
         return DbRepositoryProvider(self.env).repository_attrs
Example #38
0
    def install(self):
        options = self.options

        # create our run scripts
        entry_points = [('trac-admin', 'trac.admin.console', 'run'),
                        ('tracd', 'trac.web.standalone', 'main')]

        zc.buildout.easy_install.scripts(
                entry_points, pkg_resources.working_set,
                options['executable'], options['bin-directory']
                )
    
        # create the trac instance
        location = options['location']
        project_name = options.get('project-name', 'trac-project')
        project_name = '"%s"' % project_name
        project_url = options.get('project-url', 'http://example.com')
        if not options.has_key('db-type') or options['db-type'] == 'sqlite':
            db = 'sqlite:%s' % os.path.join('db', 'trac.db')
        elif options['db-type'] == 'postgres':
            db_options = {  'user': options['db-username'], 
                            'pass': options['db-password'], 
                            'host': options.get('db-host', 'localhost'), 
                            'db': options.get('db-name', 'trac'), 
                            'port': options.get('db-port', '5432')
                         }
            db = 'postgres://%(user)s:%(pass)s@%(host)s:%(port)s/%(db)s' % db_options

        repos_type = options.get('repos-type', "")
        repos_path = options.get('repos-path', "")

        if not os.path.exists(location):
            os.makedirs(location)

        print "Creating Trac Instance in: " + location

        
        
        # install the eggs that we need
        self.egg.install()
        
        if self.metamode:
            # put the config file somewhere so we can inherit it
            self._write_ini(os.path.join(location, 'base_trac.ini'), db, {'location': location})
            
            instances = self._get_instances()
            for instance, data in instances.iteritems():
                # we need a new location for each project
                meta_location = os.path.join(self.buildout['buildout']['directory'], 'var', self.name, instance)
                trac = TracAdmin(meta_location)
                if not trac.env_check():
                    repos_type = data.get('repository_type', '')
                    repos_path = data.get('repository-dir', '')
                    
                    # get the database dsn
                    if not data.has_key('db-type') or data['db-type'] == 'sqlite':
                        db = 'sqlite:%s' % os.path.join('db', 'trac.db')
                    elif data['db-type'] == 'postgres':
                        db_options = {  'user': data.get('db-username', 'trac'), 
                                'pass': data.get('db-password', 'trac'), 
                                'host': data.get('db-host', 'localhost'), 
                                'port': data.get('db-port', '5432'),
                                'db': instance
                             }
                        db = 'postgres://%(user)s:%(pass)s@%(host)s:%(port)s/%(db)s' % db_options
                    
                    env = trac.do_initenv('%s %s %s %s' % (instance, db, repos_type, repos_path))
                    data.update({'project_name': instance,
                                 'repository-dir': data.get('repository-dir', '')})
                    
                    data['database_dsn'] = db
                    
                    self.write_custom_config(os.path.join(meta_location, 'conf', 'trac.ini'), 
                                             os.path.join(location, 'base_trac.ini'),
                                             meta = True,
                                             meta_vars = data)
                    
                    # add any repositories
                    repo_provider = DbRepositoryProvider(trac.env)
                    repo_provider.add_repository('default', repos_path, repos_type)
            
        else:
            trac = TracAdmin(location)
            
            if not trac.env_check():
                trac.do_initenv('%s %s %s %s' % (project_name, db, repos_type, repos_path))
        
            self._write_ini(os.path.join(location, 'conf', 'base_trac.ini'), db, self.options)
            self.write_custom_config(os.path.join(location, 'conf', 'trac.ini'), os.path.join(location, 'conf', 'base_trac.ini'))

        if options.has_key('wsgi') and options['wsgi'].lower() == 'true':
            self.install_wsgi(options['location'])
            
        if options.has_key('testrunner') and options['testrunner'].lower() == 'true':
            self.install_testrunner()

        self.install_htpasswd()

        # buildout expects a tuple of paths, but we don't have any to add
        # just return an empty one for now.
        return tuple()
Example #39
0
 def setUp(self):
     self._super = super(LogModuleTestCase, self)
     self._super.setUp(LogModule)
     provider = DbRepositoryProvider(self.env)
     provider.add_repository('mock', '/', mock_repotype)
Example #40
0
class BrowserModulePermissionsTestCase(RequestHandlerPermissionsTestCaseBase):

    authz_policy = """\
[repository:*allow*@*/source:*deny*]
anonymous = !BROWSER_VIEW, !FILE_VIEW

[repository:*deny*@*/source:*allow*]
anonymous = BROWSER_VIEW, FILE_VIEW

[repository:*allow*@*]
anonymous = BROWSER_VIEW, FILE_VIEW

[repository:*deny*@*]
anonymous = !BROWSER_VIEW, !FILE_VIEW

"""

    def setUp(self):
        super(BrowserModulePermissionsTestCase, self).setUp(BrowserModule)
        provider = DbRepositoryProvider(self.env)
        provider.add_repository('(default)', '/', 'mock')
        provider.add_repository('allow', '/', 'mock')
        provider.add_repository('deny', '/', 'mock')
        provider.add_repository('raise', '/', 'mock')

    def tearDown(self):
        RepositoryManager(self.env).reload_repositories()
        super(BrowserModulePermissionsTestCase, self).tearDown()

    def test_get_navigation_items_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')
        provider = DbRepositoryProvider(self.env)
        req = MockRequest(self.env, path_info='/')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('allow')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('deny')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('(default)')
        self.assertEqual([], list(self.get_navigation_items(req)))

    def test_get_navigation_items_without_browser_view(self):
        provider = DbRepositoryProvider(self.env)
        req = MockRequest(self.env, path_info='/')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('(default)')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('deny')
        self.assertEqual('browser', self.get_navigation_items(req).next()[1])

        provider.remove_repository('allow')
        self.assertEqual([], list(self.get_navigation_items(req)))

    def test_repository_with_browser_view(self):
        self.grant_perm('anonymous', 'BROWSER_VIEW')

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/')
        rv = self.process_request(req)
        self.assertEqual('', rv[1]['repos'].name)

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/allow')
        rv = self.process_request(req)
        self.assertEqual('allow', rv[1]['repos'].name)

        req = MockRequest(self.env,
                          authname='anonymous',
                          path_info='/browser/deny')
        try:
            self.process_request(req)
            self.fail('PermissionError not raised')
        except PermissionError, e:
            self.assertEqual('BROWSER_VIEW', e.action)
            self.assertEqual('source', e.resource.realm)
            self.assertEqual('/', e.resource.id)
            self.assertEqual('repository', e.resource.parent.realm)
            self.assertEqual('deny', e.resource.parent.id)

        DbRepositoryProvider(self.env).remove_repository('(default)')
        req = MockRequest(self.env, path_info='/browser/')
        rv = self.process_request(req)
        self.assertEqual(None, rv[1]['repos'])

        req = MockRequest(self.env, path_info='/browser/blah-blah-file')
        try:
            self.process_request(req)
            self.fail('ResourceNotFound not raised')
        except ResourceNotFound, e:
            self.assertEqual('No node blah-blah-file', unicode(e))
Example #41
0
 def _dbrepoprov(self):
     return DbRepositoryProvider(self.env)
Example #42
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.db_provider = DbRepositoryProvider(self.env)