Changeset - 53eafc983b5c
[Not reviewed]
Merge beta
1 86 0
leonardo - 13 years ago 2013-03-04 18:42:14

Merge
87 files changed with 1143 insertions and 1018 deletions:
0 comments (0 inline, 0 general)
CONTRIBUTORS
Show inline comments
 
@@ -24,12 +24,13 @@ List of contributors to RhodeCode projec
 
    Indra Talip <indra.talip@gmail.com>
 
    James Rhodes <jrhodes@redpointsoftware.com.au>
 
    Dominik Ruf <dominikruf@gmail.com>
 
    xpol <xpolife@gmail.com>
 
    Vincent Caron <vcaron@bearstech.com>
 
    Zachary Auclair <zach101@gmail.com>
 
    Stefan Engel <mail@engel-stefan.de>
 
    Andrew Shadura <bugzilla@tut.by>
 
    Raoul Thill <raoul.thill@gmail.com>
 
    Philip Jameson <philip.j@hostdime.com>
 
    Mads Kiilerich <madski@unity3d.com>
 
    Dan Sheridan <djs@adelard.com>
 
    Dennis Brakhane <brakhane@googlemail.com>
README.rst
Show inline comments
 
@@ -66,25 +66,25 @@ https://github.com/marcinkuzminski/rhode
 

	
 

	
 
RhodeCode Features
 
------------------
 

	
 
- Has its own middleware to handle mercurial_ and git_ protocol requests.
 
  Each request is authenticated and logged together with IP address.
 
- Build for speed and performance. You can make multiple pulls/pushes simultaneous.
 
  Proven to work with 1000s of repositories and users
 
- Supports http/https, LDAP, AD, proxy-pass authentication.
 
- Full permissions (private/read/write/admin) together with IP restrictions for each repository,
 
  additional explicit forking and repository creation permissions.
 
- Users groups for easier permission management
 
- User groups for easier permission management
 
- Repository groups let you group repos and manage them easier.
 
- Users can fork other users repos, and compare them at any time.
 
- Integrates easily with other systems, with custom created mappers you can connect it to almost
 
  any issue tracker, and with an JSON-RPC API you can make much more
 
- Build in commit-api let's you add, edit and commit files right from RhodeCode
 
  web interface using simple editor or upload binary files using simple form.
 
- Powerfull pull-request driven review system with inline commenting,
 
  changeset statuses, and notification system.
 
- Importing and syncing repositories from remote locations for GIT_, Mercurial_ and  SVN.
 
- Mako templates let's you customize the look and feel of the application.
 
- Beautiful diffs, annotations and source code browsing all colored by pygments.
 
  Raw diffs are made in git-diff format for both VCS systems, including GIT_ binary-patches
docs/api/api.rst
Show inline comments
 
@@ -427,35 +427,35 @@ OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "msg" : "deleted user ID:<userid> <username>",
 
              "user": null
 
            }
 
    error:  null
 

	
 

	
 
get_users_group
 
---------------
 

	
 
Gets an existing users group. This command can be executed only using api_key
 
Gets an existing user group. This command can be executed only using api_key
 
belonging to user with admin rights.
 

	
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method :  "get_users_group"
 
    args :    {
 
                "usersgroupid" : "<users group id or name>"
 
                "usersgroupid" : "<user group id or name>"
 
              }
 

	
 
OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result : None if group not exist
 
             {
 
               "users_group_id" : "<id>",
 
               "group_name" :     "<groupname>",
 
               "active":          "<bool>",
 
               "members" :  [
 
                              {
 
@@ -470,25 +470,25 @@ OUTPUT::
 
                                "ldap_dn" :  "<ldap_dn>",
 
                                "last_login": "<last_login>",
 
                              },
 
                              …
 
                            ]
 
             }
 
    error : null
 

	
 

	
 
get_users_groups
 
----------------
 

	
 
Lists all existing users groups. This command can be executed only using
 
Lists all existing user groups. This command can be executed only using
 
api_key belonging to user with admin rights.
 

	
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method :  "get_users_groups"
 
    args :    { }
 

	
 
OUTPUT::
 

	
 
@@ -498,105 +498,105 @@ OUTPUT::
 
               "users_group_id" : "<id>",
 
               "group_name" :     "<groupname>",
 
               "active":          "<bool>",
 
               },
 
               …
 
              ]
 
    error : null
 

	
 

	
 
create_users_group
 
------------------
 

	
 
Creates new users group. This command can be executed only using api_key
 
Creates new user group. This command can be executed only using api_key
 
belonging to user with admin rights
 

	
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method :  "create_users_group"
 
    args:     {
 
                "group_name":  "<groupname>",
 
                "active":"<bool> = Optional(True)"
 
              }
 

	
 
OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "msg": "created new users group `<groupname>`",
 
              "msg": "created new user group `<groupname>`",
 
              "users_group": {
 
                     "users_group_id" : "<id>",
 
                     "group_name" :     "<groupname>",
 
                     "active":          "<bool>",
 
               },
 
            }
 
    error:  null
 

	
 

	
 
add_user_to_users_group
 
-----------------------
 

	
 
Adds a user to a users group. If user exists in that group success will be
 
Adds a user to a user group. If user exists in that group success will be
 
`false`. This command can be executed only using api_key
 
belonging to user with admin rights
 

	
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method :  "add_user_users_group"
 
    args:     {
 
                "usersgroupid" : "<users group id or name>",
 
                "usersgroupid" : "<user group id or name>",
 
                "userid" : "<user_id or username>",
 
              }
 

	
 
OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "success": True|False # depends on if member is in group
 
              "msg": "added member `<username>` to users group `<groupname>` |
 
              "msg": "added member `<username>` to user group `<groupname>` |
 
                      User is already in that group"
 
            }
 
    error:  null
 

	
 

	
 
remove_user_from_users_group
 
----------------------------
 

	
 
Removes a user from a users group. If user is not in given group success will
 
Removes a user from a user group. If user is not in given group success will
 
be `false`. This command can be executed only
 
using api_key belonging to user with admin rights
 

	
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method :  "remove_user_from_users_group"
 
    args:     {
 
                "usersgroupid" : "<users group id or name>",
 
                "usersgroupid" : "<user group id or name>",
 
                "userid" : "<user_id or username>",
 
              }
 

	
 
OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "success":  True|False,  # depends on if member is in group
 
              "msg": "removed member <username> from users group <groupname> |
 
              "msg": "removed member <username> from user group <groupname> |
 
                      User wasn't in group"
 
            }
 
    error:  null
 

	
 

	
 
get_repo
 
--------
 

	
 
Gets an existing repository by it's name or repository_id. Members will return
 
either users_group or user associated to that repository. This command can be
 
executed only using api_key belonging to user with admin
 
rights or regular user that have at least read access to repository.
 
@@ -920,62 +920,62 @@ OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "msg" : "Revoked perm for user: `<username>` in repo: `<reponame>`",
 
              "success": true
 
            }
 
    error:  null
 

	
 

	
 
grant_users_group_permission
 
----------------------------
 

	
 
Grant permission for users group on given repository, or update
 
Grant permission for user group on given repository, or update
 
existing one if found. This command can be executed only using
 
api_key belonging to user with admin rights.
 

	
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method :  "grant_users_group_permission"
 
    args:     {
 
                "repoid" : "<reponame or repo_id>"
 
                "usersgroupid" : "<users group id or name>"
 
                "usersgroupid" : "<user group id or name>"
 
                "perm" : "(repository.(none|read|write|admin))",
 
              }
 

	
 
OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "msg" : "Granted perm: `<perm>` for group: `<usersgroupname>` in repo: `<reponame>`",
 
              "success": true
 
            }
 
    error:  null
 

	
 

	
 
revoke_users_group_permission
 
-----------------------------
 

	
 
Revoke permission for users group on given repository.This command can be
 
Revoke permission for user group on given repository.This command can be
 
executed only using api_key belonging to user with admin rights.
 

	
 
INPUT::
 

	
 
    id : <id_for_response>
 
    api_key : "<api_key>"
 
    method  : "revoke_users_group_permission"
 
    args:     {
 
                "repoid" : "<reponame or repo_id>"
 
                "usersgroupid" : "<users group id or name>"
 
                "usersgroupid" : "<user group id or name>"
 
              }
 

	
 
OUTPUT::
 

	
 
    id : <id_given_in_input>
 
    result: {
 
              "msg" : "Revoked perm for group: `<usersgroupname>` in repo: `<reponame>`",
 
              "success": true
 
            }
 
    error:  null
docs/changelog.rst
Show inline comments
 
@@ -187,25 +187,25 @@ fixes
 

	
 
news
 
++++
 

	
 
- #558 Added config file to hooks extra data
 
- bumped mercurial version to 2.3.1
 
- #518 added possibility of specifying multiple patterns for issues
 
- update codemirror to latest version
 

	
 
fixes
 
+++++
 

	
 
- fixed #570 explicit users group permissions can overwrite owner permissions
 
- fixed #570 explicit user group permissions can overwrite owner permissions
 
- fixed #578 set proper PATH with current Python for Git
 
  hooks to execute within same Python as RhodeCode
 
- fixed issue with Git bare repos that ends with .git in name
 

	
 
1.4.2 (**2012-09-12**)
 
----------------------
 

	
 
news
 
++++
 

	
 
- added option to menu to quick lock/unlock repository for users that have
 
  write access to
 
@@ -376,25 +376,25 @@ fixes
 
1.3.4 (**2012-03-28**)
 
----------------------
 

	
 
news
 
++++
 

	
 
- Whoosh logging is now controlled by the .ini files logging setup
 
- added clone-url into edit form on /settings page
 
- added help text into repo add/edit forms
 
- created rcextensions module with additional mappings (ref #322) and
 
  post push/pull/create repo hooks callbacks
 
- implemented #377 Users view for his own permissions on account page
 
- #399 added inheritance of permissions for users group on repos groups
 
- #399 added inheritance of permissions for user group on repos groups
 
- #401 repository group is automatically pre-selected when adding repos
 
  inside a repository group
 
- added alternative HTTP 403 response when client failed to authenticate. Helps
 
  solving issues with Mercurial and LDAP
 
- #402 removed group prefix from repository name when listing repositories
 
  inside a group
 
- added gravatars into permission view and permissions autocomplete
 
- #347 when running multiple RhodeCode instances, properly invalidates cache
 
  for all registered servers
 

	
 
fixes
 
+++++
 
@@ -511,25 +511,25 @@ fixes
 
+++++
 

	
 
- rewrote dbsession management for atomic operations, and better error handling
 
- fixed sorting of repo tables
 
- #326 escape of special html entities in diffs
 
- normalized user_name => username in api attributes
 
- fixes #298 ldap created users with mixed case emails created conflicts
 
  on saving a form
 
- fixes issue when owner of a repo couldn't revoke permissions for users
 
  and groups
 
- fixes #271 rare JSON serialization problem with statistics
 
- fixes #337 missing validation check for conflicting names of a group with a
 
  repositories group
 
  repository group
 
- #340 fixed session problem for mysql and celery tasks
 
- fixed #331 RhodeCode mangles repository names if the a repository group
 
  contains the "full path" to the repositories
 
- #355 RhodeCode doesn't store encrypted LDAP passwords
 

	
 
1.2.5 (**2012-01-28**)
 
----------------------
 

	
 
news
 
++++
 

	
 
fixes
 
@@ -645,25 +645,25 @@ news
 
  like tags, branches
 
- implemented #44 into file browsing, and added follow branch option
 
- implemented #84 downloads can be enabled/disabled for each repository
 
- anonymous repository can be cloned without having to pass default:default
 
  into clone url
 
- fixed #90 whoosh indexer can index chooses repositories passed in command
 
  line
 
- extended journal with day aggregates and paging
 
- implemented #107 source code lines highlight ranges
 
- implemented #93 customizable changelog on combined revision ranges -
 
  equivalent of githubs compare view
 
- implemented #108 extended and more powerful LDAP configuration
 
- implemented #56 users groups
 
- implemented #56 user groups
 
- major code rewrites optimized codes for speed and memory usage
 
- raw and diff downloads are now in git format
 
- setup command checks for write access to given path
 
- fixed many issues with international characters and unicode. It uses utf8
 
  decode with replace to provide less errors even with non utf8 encoded strings
 
- #125 added API KEY access to feeds
 
- #109 Repository can be created from external Mercurial link (aka. remote
 
  repository, and manually updated (via pull) from admin panel
 
- beta git support - push/pull server + basic view for git repos
 
- added followers page and forks page
 
- server side file creation (with binary file upload interface)
 
  and edition with commits powered by codemirror
docs/installation_win.rst
Show inline comments
 
@@ -38,25 +38,25 @@ choose "Visual C++ 2008 Express" when in
 

	
 
.. note::
 

	
 
   Using other versions of Visual Studio will lead to random crashes.
 
   You must use Visual Studio 2008!"
 

	
 
.. note::
 

	
 
   Silverlight Runtime and SQL Server 2008 Express Edition are not
 
   required, you can uncheck them
 

	
 
.. note::
 
   
 

	
 
   64bit: You also need to install the Microsoft Windows SDK for .NET 3.5 SP1 (.NET 4.0 won't work).
 
   Download from: http://www.microsoft.com/en-us/download/details.aspx?id=3138
 

	
 
.. note::
 

	
 
   64bit: You also need to copy and rename a .bat file to make the Visual C++ compiler work.
 
   I am not sure why this is not necessary for 32bit.
 
   Copy C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars64.bat to C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64\vcvarsamd64.bat
 

	
 

	
 
Step2 - Install Python
 
----------------------
 
@@ -81,25 +81,25 @@ Download pywin32 from:
 
http://sourceforge.net/projects/pywin32/files/
 

	
 
- Click on "pywin32" folder
 
- Click on the first folder (in this case, Build 217, maybe newer when you try)
 
- Choose the file ending with ".win32-py2.x.exe" -> x being the minor
 
  version of Python you installed (in this case, 7)
 
  When writing this guide, the file was:
 
  http://sourceforge.net/projects/pywin32/files/pywin32/Build%20217/pywin32-217.win32-py2.7.exe/download
 

	
 
  .. note::
 

	
 
     64bit: Download and install the 64bit version.
 
     At the time of writing you can find this at: 
 
     At the time of writing you can find this at:
 
     http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win-amd64-py2.7.exe/download
 

	
 
Step4 - Python BIN
 
------------------
 

	
 
Add Python BIN folder to the path
 

	
 
You have to add the Python folder to the path, you can do it manually
 
(editing "PATH" environment variable) or using Windows Support Tools
 
that came preinstalled in Vista/7 and can be installed in Windows XP.
 

	
 
- Using support tools on WINDOWS XP:
docs/theme/nature/static/pygments.css
Show inline comments
 
@@ -42,13 +42,13 @@
 
.s2 { color: #bb8844 } /* Literal.String.Double */
 
.se { color: #bb8844 } /* Literal.String.Escape */
 
.sh { color: #bb8844 } /* Literal.String.Heredoc */
 
.si { color: #bb8844 } /* Literal.String.Interpol */
 
.sx { color: #bb8844 } /* Literal.String.Other */
 
.sr { color: #808000 } /* Literal.String.Regex */
 
.s1 { color: #bb8844 } /* Literal.String.Single */
 
.ss { color: #bb8844 } /* Literal.String.Symbol */
 
.bp { color: #999999 } /* Name.Builtin.Pseudo */
 
.vc { color: #ff99ff } /* Name.Variable.Class */
 
.vg { color: #ff99ff } /* Name.Variable.Global */
 
.vi { color: #ff99ff } /* Name.Variable.Instance */
 
.il { color: #009999 } /* Literal.Number.Integer.Long */
 
\ No newline at end of file
 
.il { color: #009999 } /* Literal.Number.Integer.Long */
docs/usage/performance.rst
Show inline comments
 
@@ -37,28 +37,26 @@ Follow these few steps to improve perfor
 

	
 
    sqlite is a good option when having small load on the system. But due to
 
    locking issues with sqlite, it's not recommended to use it for larger
 
    setup. Switching to mysql or postgres will result in a immediate
 
    performance increase.
 

	
 
3. Scale RhodeCode horizontally
 

	
 
    Scaling horizontally can give huge performance increase when dealing with
 
    large traffic (large amount of users, CI servers etc). RhodeCode can be
 
    scaled horizontally on one (recommended) or multiple machines. In order
 
    to scale horizontally you need to do the following:
 
    
 

	
 
    - each instance needs it's own .ini file and unique `instance_id` set in them
 
    - each instance `data` storage needs to be configured to be stored on a 
 
    - each instance `data` storage needs to be configured to be stored on a
 
      shared disk storage, preferably together with repositories. This `data`
 
      dir contains template caches, sessions, whoosh index and it's used for
 
      tasks locking (so it's safe across multiple instances). Set the
 
      `cache_dir`, `index_dir`, `beaker.cache.data_dir`, `beaker.cache.lock_dir`
 
      variables in each .ini file to shared location across RhodeCode instances 
 
      variables in each .ini file to shared location across RhodeCode instances
 
    - if celery is used each instance should run separate celery instance, but
 
      the message broken should be common to all of them (ex one rabbitmq
 
      shared server)    
 
      shared server)
 
    - load balance using round robin or ip hash, recommended is writing LB rules
 
      that will separate regular user traffic from automated processes like CI
 
      servers or build bots.
 

	
 

	
requires.txt
Show inline comments
 
deleted file
rhodecode/config/routing.py
Show inline comments
 
@@ -39,25 +39,25 @@ def make_map(config):
 
        try:
 
            by_id = repo_name.split('_')
 
            if len(by_id) == 2 and by_id[1].isdigit() and by_id[0] == '':
 
                repo_name = Repository.get(by_id[1]).repo_name
 
                match_dict['repo_name'] = repo_name
 
        except:
 
            pass
 

	
 
        return is_valid_repo(repo_name, config['base_path'])
 

	
 
    def check_group(environ, match_dict):
 
        """
 
        check for valid repositories group for proper 404 handling
 
        check for valid repository group for proper 404 handling
 

	
 
        :param environ:
 
        :param match_dict:
 
        """
 
        repos_group_name = match_dict.get('group_name')
 
        return is_valid_repos_group(repos_group_name, config['base_path'])
 

	
 
    def check_int(environ, match_dict):
 
        return match_dict.get('id').isdigit()
 

	
 
    # The ErrorController route (handles 404/500 error pages); it should
 
    # likely stay at the top, ensuring it can always be resolved
 
@@ -226,25 +226,25 @@ def make_map(config):
 
        #EXTRAS USER ROUTES
 
        m.connect("user_perm", "/users_perm/{id}",
 
                  action="update_perm", conditions=dict(method=["PUT"]))
 
        m.connect("user_emails", "/users_emails/{id}",
 
                  action="add_email", conditions=dict(method=["PUT"]))
 
        m.connect("user_emails_delete", "/users_emails/{id}",
 
                  action="delete_email", conditions=dict(method=["DELETE"]))
 
        m.connect("user_ips", "/users_ips/{id}",
 
                  action="add_ip", conditions=dict(method=["PUT"]))
 
        m.connect("user_ips_delete", "/users_ips/{id}",
 
                  action="delete_ip", conditions=dict(method=["DELETE"]))
 

	
 
    #ADMIN USERS GROUPS REST ROUTES
 
    #ADMIN USER GROUPS REST ROUTES
 
    with rmap.submapper(path_prefix=ADMIN_PREFIX,
 
                        controller='admin/users_groups') as m:
 
        m.connect("users_groups", "/users_groups",
 
                  action="create", conditions=dict(method=["POST"]))
 
        m.connect("users_groups", "/users_groups",
 
                  action="index", conditions=dict(method=["GET"]))
 
        m.connect("formatted_users_groups", "/users_groups.{format}",
 
                  action="index", conditions=dict(method=["GET"]))
 
        m.connect("new_users_group", "/users_groups/new",
 
                  action="new", conditions=dict(method=["GET"]))
 
        m.connect("formatted_new_users_group", "/users_groups/new.{format}",
 
                  action="new", conditions=dict(method=["GET"]))
rhodecode/controllers/admin/notifications.py
Show inline comments
 
@@ -19,25 +19,25 @@
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import traceback
 

	
 
from pylons import request
 
from pylons import tmpl_context as c, url
 
from pylons.controllers.util import redirect
 
from pylons.controllers.util import redirect, abort
 

	
 
from webhelpers.paginate import Page
 

	
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.model.db import Notification
 

	
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.lib.auth import LoginRequired, NotAnonymous
 
from rhodecode.lib import helpers as h
 
from rhodecode.model.meta import Session
 
from rhodecode.lib.utils2 import safe_int
 

	
 
@@ -108,65 +108,66 @@ class NotificationsController(BaseContro
 
        #    h.form(url('notification', notification_id=ID),
 
        #           method='put')
 
        # url('notification', notification_id=ID)
 
        try:
 
            no = Notification.get(notification_id)
 
            owner = all(un.user.user_id == c.rhodecode_user.user_id
 
                        for un in no.notifications_to_users)
 
            if h.HasPermissionAny('hg.admin')() or owner:
 
                    NotificationModel().mark_read(c.rhodecode_user.user_id, no)
 
                    Session().commit()
 
                    return 'ok'
 
        except Exception:
 
            Session.rollback()
 
            Session().rollback()
 
            log.error(traceback.format_exc())
 
        return 'fail'
 

	
 
    def delete(self, notification_id):
 
        """DELETE /_admin/notifications/id: Delete an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="DELETE" />
 
        # Or using helpers:
 
        #    h.form(url('notification', notification_id=ID),
 
        #           method='delete')
 
        # url('notification', notification_id=ID)
 

	
 
        try:
 
            no = Notification.get(notification_id)
 
            owner = all(un.user.user_id == c.rhodecode_user.user_id
 
                        for un in no.notifications_to_users)
 
            if h.HasPermissionAny('hg.admin')() or owner:
 
                    NotificationModel().delete(c.rhodecode_user.user_id, no)
 
                    Session().commit()
 
                    return 'ok'
 
        except Exception:
 
            Session.rollback()
 
            Session().rollback()
 
            log.error(traceback.format_exc())
 
        return 'fail'
 

	
 
    def show(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id: Show a specific item"""
 
        # url('notification', notification_id=ID)
 
        c.user = self.rhodecode_user
 
        no = Notification.get(notification_id)
 

	
 
        owner = all(un.user.user_id == c.rhodecode_user.user_id
 
        owner = any(un.user.user_id == c.rhodecode_user.user_id
 
                    for un in no.notifications_to_users)
 

	
 
        if no and (h.HasPermissionAny('hg.admin', 'repository.admin')() or owner):
 
            unotification = NotificationModel()\
 
                            .get_user_notification(c.user.user_id, no)
 

	
 
            # if this association to user is not valid, we don't want to show
 
            # this message
 
            if unotification:
 
                if unotification.read is False:
 
                    unotification.mark_as_read()
 
                    Session().commit()
 
                c.notification = no
 

	
 
                return render('admin/notifications/show_notification.html')
 

	
 
        return redirect(url('notifications'))
 
        return abort(403)
 

	
 
    def edit(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id/edit: Form to edit an existing item"""
 
        # url('edit_notification', notification_id=ID)
rhodecode/controllers/admin/repos.py
Show inline comments
 
@@ -336,38 +336,38 @@ class ReposController(BaseRepoController
 
            RepoModel().revoke_user_permission(repo=repo_name,
 
                                               user=request.POST['user_id'])
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of repository user'),
 
                    category='error')
 
            raise HTTPInternalServerError()
 

	
 
    @HasRepoPermissionAllDecorator('repository.admin')
 
    def delete_perm_users_group(self, repo_name):
 
        """
 
        DELETE an existing repository permission users group
 
        DELETE an existing repository permission user group
 

	
 
        :param repo_name:
 
        """
 

	
 
        try:
 
            RepoModel().revoke_users_group_permission(
 
                repo=repo_name, group_name=request.POST['users_group_id']
 
            )
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of repository'
 
                      ' users groups'),
 
                      ' user groups'),
 
                    category='error')
 
            raise HTTPInternalServerError()
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def repo_stats(self, repo_name):
 
        """
 
        DELETE an existing repository statistics
 

	
 
        :param repo_name:
 
        """
 

	
 
        try:
rhodecode/controllers/admin/repos_groups.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.controllers.admin.repos_groups
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Repositories groups controller for RhodeCode
 
    Repository groups controller for RhodeCode
 

	
 
    :created_on: Mar 23, 2010
 
    :author: marcink
 
    :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
@@ -273,65 +273,65 @@ class ReposGroupsController(BaseControll
 
                          'group %s') % gr.group_name, category='error')
 

	
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during deletion of repos '
 
                      'group %s') % gr.group_name, category='error')
 

	
 
        return redirect(url('repos_groups'))
 

	
 
    @HasReposGroupPermissionAnyDecorator('group.admin')
 
    def delete_repos_group_user_perm(self, group_name):
 
        """
 
        DELETE an existing repositories group permission user
 
        DELETE an existing repository group permission user
 

	
 
        :param group_name:
 
        """
 
        try:
 
            if not c.rhodecode_user.is_admin:
 
                if c.rhodecode_user.user_id == safe_int(request.POST['user_id']):
 
                    msg = _('Cannot revoke permission for yourself as admin')
 
                    h.flash(msg, category='warning')
 
                    raise Exception('revoke admin permission on self')
 
            recursive = str2bool(request.POST.get('recursive', False))
 
            ReposGroupModel().delete_permission(
 
                repos_group=group_name, obj=request.POST['user_id'],
 
                obj_type='user', recursive=recursive
 
            )
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of group user'),
 
                    category='error')
 
            raise HTTPInternalServerError()
 

	
 
    @HasReposGroupPermissionAnyDecorator('group.admin')
 
    def delete_repos_group_users_group_perm(self, group_name):
 
        """
 
        DELETE an existing repositories group permission users group
 
        DELETE an existing repository group permission user group
 

	
 
        :param group_name:
 
        """
 

	
 
        try:
 
            recursive = str2bool(request.POST.get('recursive', False))
 
            ReposGroupModel().delete_permission(
 
                repos_group=group_name, obj=request.POST['users_group_id'],
 
                obj_type='users_group', recursive=recursive
 
            )
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of group'
 
                      ' users groups'),
 
                      ' user groups'),
 
                    category='error')
 
            raise HTTPInternalServerError()
 

	
 
    def show_by_name(self, group_name):
 
        """
 
        This is a proxy that does a lookup group_name -> id, and shows
 
        the group by id view instead
 
        """
 
        group_name = group_name.rstrip('/')
 
        id_ = RepoGroup.get_by_group_name(group_name)
 
        if id_:
 
            return self.show(id_.group_id)
rhodecode/controllers/admin/settings.py
Show inline comments
 
@@ -465,36 +465,41 @@ class SettingsController(BaseController)
 
                prefix_error=False,
 
                encoding="UTF-8")
 
            return render('admin/users/user_edit_my_account.html')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during update of user %s') \
 
                    % form_result.get('username'), category='error')
 

	
 
        return redirect(url('my_account'))
 

	
 
    @NotAnonymous()
 
    def my_account_my_pullrequests(self):
 
        c.my_pull_requests = PullRequest.query()\
 
        c.show_closed = request.GET.get('pr_show_closed')
 

	
 
        def _filter(pr):
 
            s = sorted(pr, key=lambda o: o.created_on, reverse=True)
 
            if not c.show_closed:
 
                s = filter(lambda p: p.status != PullRequest.STATUS_CLOSED, s)
 
            return s
 

	
 
        c.my_pull_requests = _filter(PullRequest.query()\
 
                                .filter(PullRequest.user_id ==
 
                                        self.rhodecode_user.user_id)\
 
                                .order_by(PullRequest.created_on.desc())\
 
                                .all()
 
                                .all())
 

	
 
        c.participate_in_pull_requests = sorted(
 
            [x.pull_request for x in PullRequestReviewers.query()\
 
                                    .filter(PullRequestReviewers.user_id ==
 
                                            self.rhodecode_user.user_id)\
 
                                    .all()],
 
                                    key=lambda o: o.created_on, reverse=True)
 
        c.participate_in_pull_requests = _filter([
 
                    x.pull_request for x in PullRequestReviewers.query()\
 
                    .filter(PullRequestReviewers.user_id ==
 
                            self.rhodecode_user.user_id).all()])
 

	
 
        return render('admin/users/user_edit_my_account_pullrequests.html')
 

	
 
    @NotAnonymous()
 
    def create_repository(self):
 
        """GET /_admin/create_repository: Form to create a new item"""
 
        new_repo = request.GET.get('repo', '')
 
        parent_group = request.GET.get('parent_group')
 
        if not HasPermissionAny('hg.admin', 'hg.create.repository')():
 
            #you're not super admin nor have global create permissions,
 
            #but maybe you have at least write permission to a parent group ?
 
            _gr = RepoGroup.get(parent_group)
rhodecode/controllers/admin/users_groups.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.controllers.admin.users_groups
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Users Groups crud controller for pylons
 
    User Groups crud controller for pylons
 

	
 
    :created_on: Jan 25, 2011
 
    :author: marcink
 
    :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
@@ -24,259 +24,259 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import traceback
 
import formencode
 

	
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, config
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 
from rhodecode.lib.exceptions import UserGroupsAssignedException
 
from rhodecode.lib.utils2 import safe_unicode, str2bool
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
 
from rhodecode.lib.base import BaseController, render
 

	
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 

	
 
from rhodecode.model.db import User, UsersGroup, UsersGroupToPerm,\
 
    UsersGroupRepoToPerm, UsersGroupRepoGroupToPerm
 
from rhodecode.model.forms import UsersGroupForm
 
from rhodecode.model.db import User, UserGroup, UserGroupToPerm,\
 
    UserGroupRepoToPerm, UserGroupRepoGroupToPerm
 
from rhodecode.model.forms import UserGroupForm
 
from rhodecode.model.meta import Session
 
from rhodecode.lib.utils import action_logger
 
from sqlalchemy.orm import joinedload
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersGroupsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('users_group', 'users_groups')
 

	
 
    @LoginRequired()
 
    @HasPermissionAllDecorator('hg.admin')
 
    def __before__(self):
 
        c.admin_user = session.get('admin_user')
 
        c.admin_username = session.get('admin_username')
 
        super(UsersGroupsController, self).__before__()
 
        c.available_permissions = config['available_permissions']
 

	
 
    def index(self, format='html'):
 
        """GET /users_groups: All items in the collection"""
 
        # url('users_groups')
 
        c.users_groups_list = UsersGroup().query().all()
 
        c.users_groups_list = UserGroup().query().all()
 
        return render('admin/users_groups/users_groups.html')
 

	
 
    def create(self):
 
        """POST /users_groups: Create a new item"""
 
        # url('users_groups')
 

	
 
        users_group_form = UsersGroupForm()()
 
        users_group_form = UserGroupForm()()
 
        try:
 
            form_result = users_group_form.to_python(dict(request.POST))
 
            UsersGroupModel().create(name=form_result['users_group_name'],
 
            UserGroupModel().create(name=form_result['users_group_name'],
 
                                     active=form_result['users_group_active'])
 
            gr = form_result['users_group_name']
 
            action_logger(self.rhodecode_user,
 
                          'admin_created_users_group:%s' % gr,
 
                          None, self.ip_addr, self.sa)
 
            h.flash(_('created users group %s') % gr, category='success')
 
            h.flash(_('created user group %s') % gr, category='success')
 
            Session().commit()
 
        except formencode.Invalid, errors:
 
            return htmlfill.render(
 
                render('admin/users_groups/users_group_add.html'),
 
                defaults=errors.value,
 
                errors=errors.error_dict or {},
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during creation of users group %s') \
 
            h.flash(_('error occurred during creation of user group %s') \
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        return redirect(url('users_groups'))
 

	
 
    def new(self, format='html'):
 
        """GET /users_groups/new: Form to create a new item"""
 
        # url('new_users_group')
 
        return render('admin/users_groups/users_group_add.html')
 

	
 
    def _load_data(self, id):
 
        c.users_group.permissions = {
 
            'repositories': {},
 
            'repositories_groups': {}
 
        }
 

	
 
        ugroup_repo_perms = UsersGroupRepoToPerm.query()\
 
            .options(joinedload(UsersGroupRepoToPerm.permission))\
 
            .options(joinedload(UsersGroupRepoToPerm.repository))\
 
            .filter(UsersGroupRepoToPerm.users_group_id == id)\
 
        ugroup_repo_perms = UserGroupRepoToPerm.query()\
 
            .options(joinedload(UserGroupRepoToPerm.permission))\
 
            .options(joinedload(UserGroupRepoToPerm.repository))\
 
            .filter(UserGroupRepoToPerm.users_group_id == id)\
 
            .all()
 

	
 
        for gr in ugroup_repo_perms:
 
            c.users_group.permissions['repositories'][gr.repository.repo_name]  \
 
                = gr.permission.permission_name
 

	
 
        ugroup_group_perms = UsersGroupRepoGroupToPerm.query()\
 
            .options(joinedload(UsersGroupRepoGroupToPerm.permission))\
 
            .options(joinedload(UsersGroupRepoGroupToPerm.group))\
 
            .filter(UsersGroupRepoGroupToPerm.users_group_id == id)\
 
        ugroup_group_perms = UserGroupRepoGroupToPerm.query()\
 
            .options(joinedload(UserGroupRepoGroupToPerm.permission))\
 
            .options(joinedload(UserGroupRepoGroupToPerm.group))\
 
            .filter(UserGroupRepoGroupToPerm.users_group_id == id)\
 
            .all()
 

	
 
        for gr in ugroup_group_perms:
 
            c.users_group.permissions['repositories_groups'][gr.group.group_name] \
 
                = gr.permission.permission_name
 

	
 
        c.group_members_obj = [x.user for x in c.users_group.members]
 
        c.group_members = [(x.user_id, x.username) for x in
 
                           c.group_members_obj]
 
        c.available_members = [(x.user_id, x.username) for x in
 
                               User.query().all()]
 

	
 
    def update(self, id):
 
        """PUT /users_groups/id: Update an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="PUT" />
 
        # Or using helpers:
 
        #    h.form(url('users_group', id=ID),
 
        #           method='put')
 
        # url('users_group', id=ID)
 

	
 
        c.users_group = UsersGroup.get_or_404(id)
 
        c.users_group = UserGroup.get_or_404(id)
 
        self._load_data(id)
 

	
 
        available_members = [safe_unicode(x[0]) for x in c.available_members]
 

	
 
        users_group_form = UsersGroupForm(edit=True,
 
        users_group_form = UserGroupForm(edit=True,
 
                                          old_data=c.users_group.get_dict(),
 
                                          available_members=available_members)()
 

	
 
        try:
 
            form_result = users_group_form.to_python(request.POST)
 
            UsersGroupModel().update(c.users_group, form_result)
 
            UserGroupModel().update(c.users_group, form_result)
 
            gr = form_result['users_group_name']
 
            action_logger(self.rhodecode_user,
 
                          'admin_updated_users_group:%s' % gr,
 
                          None, self.ip_addr, self.sa)
 
            h.flash(_('updated users group %s') % gr, category='success')
 
            h.flash(_('updated user group %s') % gr, category='success')
 
            Session().commit()
 
        except formencode.Invalid, errors:
 
            ug_model = UsersGroupModel()
 
            ug_model = UserGroupModel()
 
            defaults = errors.value
 
            e = errors.error_dict or {}
 
            defaults.update({
 
                'create_repo_perm': ug_model.has_perm(id,
 
                                                      'hg.create.repository'),
 
                'fork_repo_perm': ug_model.has_perm(id,
 
                                                    'hg.fork.repository'),
 
                '_method': 'put'
 
            })
 

	
 
            return htmlfill.render(
 
                render('admin/users_groups/users_group_edit.html'),
 
                defaults=defaults,
 
                errors=e,
 
                prefix_error=False,
 
                encoding="UTF-8")
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('error occurred during update of users group %s') \
 
            h.flash(_('error occurred during update of user group %s') \
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        return redirect(url('edit_users_group', id=id))
 

	
 
    def delete(self, id):
 
        """DELETE /users_groups/id: Delete an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="DELETE" />
 
        # Or using helpers:
 
        #    h.form(url('users_group', id=ID),
 
        #           method='delete')
 
        # url('users_group', id=ID)
 
        usr_gr = UsersGroup.get_or_404(id)
 
        usr_gr = UserGroup.get_or_404(id)
 
        try:
 
            UsersGroupModel().delete(usr_gr)
 
            UserGroupModel().delete(usr_gr)
 
            Session().commit()
 
            h.flash(_('successfully deleted users group'), category='success')
 
        except UsersGroupsAssignedException, e:
 
            h.flash(_('successfully deleted user group'), category='success')
 
        except UserGroupsAssignedException, e:
 
            h.flash(e, category='error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during deletion of users group'),
 
            h.flash(_('An error occurred during deletion of user group'),
 
                    category='error')
 
        return redirect(url('users_groups'))
 

	
 
    def show(self, id, format='html'):
 
        """GET /users_groups/id: Show a specific item"""
 
        # url('users_group', id=ID)
 

	
 
    def edit(self, id, format='html'):
 
        """GET /users_groups/id/edit: Form to edit an existing item"""
 
        # url('edit_users_group', id=ID)
 

	
 
        c.users_group = UsersGroup.get_or_404(id)
 
        c.users_group = UserGroup.get_or_404(id)
 
        self._load_data(id)
 

	
 
        ug_model = UsersGroupModel()
 
        ug_model = UserGroupModel()
 
        defaults = c.users_group.get_dict()
 
        defaults.update({
 
            'create_repo_perm': ug_model.has_perm(c.users_group,
 
                                                  'hg.create.repository'),
 
            'fork_repo_perm': ug_model.has_perm(c.users_group,
 
                                                'hg.fork.repository'),
 
        })
 

	
 
        return htmlfill.render(
 
            render('admin/users_groups/users_group_edit.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )
 

	
 
    def update_perm(self, id):
 
        """PUT /users_perm/id: Update an existing item"""
 
        # url('users_group_perm', id=ID, method='put')
 

	
 
        users_group = UsersGroup.get_or_404(id)
 
        users_group = UserGroup.get_or_404(id)
 
        grant_create_perm = str2bool(request.POST.get('create_repo_perm'))
 
        grant_fork_perm = str2bool(request.POST.get('fork_repo_perm'))
 
        inherit_perms = str2bool(request.POST.get('inherit_default_permissions'))
 

	
 
        usersgroup_model = UsersGroupModel()
 
        usergroup_model = UserGroupModel()
 

	
 
        try:
 
            users_group.inherit_default_permissions = inherit_perms
 
            Session().add(users_group)
 

	
 
            if grant_create_perm:
 
                usersgroup_model.revoke_perm(id, 'hg.create.none')
 
                usersgroup_model.grant_perm(id, 'hg.create.repository')
 
                h.flash(_("Granted 'repository create' permission to users group"),
 
                usergroup_model.revoke_perm(id, 'hg.create.none')
 
                usergroup_model.grant_perm(id, 'hg.create.repository')
 
                h.flash(_("Granted 'repository create' permission to user group"),
 
                        category='success')
 
            else:
 
                usersgroup_model.revoke_perm(id, 'hg.create.repository')
 
                usersgroup_model.grant_perm(id, 'hg.create.none')
 
                h.flash(_("Revoked 'repository create' permission to users group"),
 
                usergroup_model.revoke_perm(id, 'hg.create.repository')
 
                usergroup_model.grant_perm(id, 'hg.create.none')
 
                h.flash(_("Revoked 'repository create' permission to user group"),
 
                        category='success')
 

	
 
            if grant_fork_perm:
 
                usersgroup_model.revoke_perm(id, 'hg.fork.none')
 
                usersgroup_model.grant_perm(id, 'hg.fork.repository')
 
                h.flash(_("Granted 'repository fork' permission to users group"),
 
                usergroup_model.revoke_perm(id, 'hg.fork.none')
 
                usergroup_model.grant_perm(id, 'hg.fork.repository')
 
                h.flash(_("Granted 'repository fork' permission to user group"),
 
                        category='success')
 
            else:
 
                usersgroup_model.revoke_perm(id, 'hg.fork.repository')
 
                usersgroup_model.grant_perm(id, 'hg.fork.none')
 
                h.flash(_("Revoked 'repository fork' permission to users group"),
 
                usergroup_model.revoke_perm(id, 'hg.fork.repository')
 
                usergroup_model.grant_perm(id, 'hg.fork.none')
 
                h.flash(_("Revoked 'repository fork' permission to user group"),
 
                        category='success')
 

	
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('An error occurred during permissions saving'),
 
                    category='error')
 

	
 
        return redirect(url('edit_users_group', id=id))
rhodecode/controllers/api/api.py
Show inline comments
 
@@ -25,29 +25,30 @@
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 

	
 
import traceback
 
import logging
 
from pylons.controllers.util import abort
 

	
 
from rhodecode.controllers.api import JSONRPCController, JSONRPCError
 
from rhodecode.lib.auth import PasswordGenerator, AuthUser, \
 
    HasPermissionAllDecorator, HasPermissionAnyDecorator, \
 
    HasPermissionAnyApi, HasRepoPermissionAnyApi
 
from rhodecode.lib.utils import map_groups, repo2db_mapper
 
from rhodecode.lib.utils2 import str2bool
 
from rhodecode.model.meta import Session
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 
from rhodecode.model.permission import PermissionModel
 
from rhodecode.model.db import Repository, RhodeCodeSetting, UserIpMap
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class OptionalAttr(object):
 
    """
 
    Special Optional Option that defines other attribute
 
    """
 
    def __init__(self, attr_name):
 
        self.attr_name = attr_name
 
@@ -112,31 +113,31 @@ def get_repo_or_error(repoid):
 
    Get repo by id or name or return JsonRPCError if not found
 

	
 
    :param userid:
 
    """
 
    repo = RepoModel().get_repo(repoid)
 
    if repo is None:
 
        raise JSONRPCError('repository `%s` does not exist' % (repoid))
 
    return repo
 

	
 

	
 
def get_users_group_or_error(usersgroupid):
 
    """
 
    Get users group by id or name or return JsonRPCError if not found
 
    Get user group by id or name or return JsonRPCError if not found
 

	
 
    :param userid:
 
    """
 
    users_group = UsersGroupModel().get_group(usersgroupid)
 
    users_group = UserGroupModel().get_group(usersgroupid)
 
    if users_group is None:
 
        raise JSONRPCError('users group `%s` does not exist' % usersgroupid)
 
        raise JSONRPCError('user group `%s` does not exist' % usersgroupid)
 
    return users_group
 

	
 

	
 
def get_perm_or_error(permid):
 
    """
 
    Get permission by id or name or return JsonRPCError if not found
 

	
 
    :param userid:
 
    """
 
    perm = PermissionModel().get_permission_by_name(permid)
 
    if perm is None:
 
        raise JSONRPCError('permission `%s` does not exist' % (permid))
 
@@ -248,25 +249,25 @@ class ApiController(JSONRPCController):
 
            #make sure normal user does not pass someone else userid,
 
            #he is not allowed to do that
 
            if not isinstance(userid, Optional) and userid != apiuser.user_id:
 
                raise JSONRPCError(
 
                    'userid is not the same as your user'
 
                )
 
        else:
 
            raise JSONRPCError('repository `%s` does not exist' % (repoid))
 

	
 
        if isinstance(userid, Optional):
 
            userid = apiuser.user_id
 
        user = get_user_or_error(userid)
 
        locked = bool(locked)
 
        locked = str2bool(locked)
 
        try:
 
            if locked:
 
                Repository.lock(repo, user.user_id)
 
            else:
 
                Repository.unlock(repo)
 

	
 
            return ('User `%s` set lock state for repo `%s` to `%s`'
 
                    % (user.username, repo.repo_name, locked))
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'Error occurred locking repository `%s`' % repo.repo_name
 
@@ -440,136 +441,136 @@ class ApiController(JSONRPCController):
 
            return dict(
 
                msg='deleted user ID:%s %s' % (user.user_id, user.username),
 
                user=None
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to delete ID:%s %s' % (user.user_id,
 
                                                              user.username))
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def get_users_group(self, apiuser, usersgroupid):
 
        """"
 
        Get users group by name or id
 
        Get user group by name or id
 

	
 
        :param apiuser:
 
        :param usersgroupid:
 
        """
 
        users_group = get_users_group_or_error(usersgroupid)
 

	
 
        data = users_group.get_api_data()
 

	
 
        members = []
 
        for user in users_group.members:
 
            user = user.user
 
            members.append(user.get_api_data())
 
        data['members'] = members
 
        return data
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def get_users_groups(self, apiuser):
 
        """"
 
        Get all users groups
 
        Get all user groups
 

	
 
        :param apiuser:
 
        """
 

	
 
        result = []
 
        for users_group in UsersGroupModel().get_all():
 
        for users_group in UserGroupModel().get_all():
 
            result.append(users_group.get_api_data())
 
        return result
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def create_users_group(self, apiuser, group_name, active=Optional(True)):
 
        """
 
        Creates an new usergroup
 

	
 
        :param apiuser:
 
        :param group_name:
 
        :param active:
 
        """
 

	
 
        if UsersGroupModel().get_by_name(group_name):
 
            raise JSONRPCError("users group `%s` already exist" % group_name)
 
        if UserGroupModel().get_by_name(group_name):
 
            raise JSONRPCError("user group `%s` already exist" % group_name)
 

	
 
        try:
 
            active = Optional.extract(active)
 
            ug = UsersGroupModel().create(name=group_name, active=active)
 
            ug = UserGroupModel().create(name=group_name, active=active)
 
            Session().commit()
 
            return dict(
 
                msg='created new users group `%s`' % group_name,
 
                msg='created new user group `%s`' % group_name,
 
                users_group=ug.get_api_data()
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError('failed to create group `%s`' % group_name)
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def add_user_to_users_group(self, apiuser, usersgroupid, userid):
 
        """"
 
        Add a user to a users group
 
        Add a user to a user group
 

	
 
        :param apiuser:
 
        :param usersgroupid:
 
        :param userid:
 
        """
 
        user = get_user_or_error(userid)
 
        users_group = get_users_group_or_error(usersgroupid)
 

	
 
        try:
 
            ugm = UsersGroupModel().add_user_to_group(users_group, user)
 
            ugm = UserGroupModel().add_user_to_group(users_group, user)
 
            success = True if ugm != True else False
 
            msg = 'added member `%s` to users group `%s`' % (
 
            msg = 'added member `%s` to user group `%s`' % (
 
                        user.username, users_group.users_group_name
 
                    )
 
            msg = msg if success else 'User is already in that group'
 
            Session().commit()
 

	
 
            return dict(
 
                success=success,
 
                msg=msg
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'failed to add member to users group `%s`' % (
 
                'failed to add member to user group `%s`' % (
 
                    users_group.users_group_name
 
                )
 
            )
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def remove_user_from_users_group(self, apiuser, usersgroupid, userid):
 
        """
 
        Remove user from a group
 

	
 
        :param apiuser:
 
        :param usersgroupid:
 
        :param userid:
 
        """
 
        user = get_user_or_error(userid)
 
        users_group = get_users_group_or_error(usersgroupid)
 

	
 
        try:
 
            success = UsersGroupModel().remove_user_from_group(users_group,
 
            success = UserGroupModel().remove_user_from_group(users_group,
 
                                                               user)
 
            msg = 'removed member `%s` from users group `%s`' % (
 
            msg = 'removed member `%s` from user group `%s`' % (
 
                        user.username, users_group.users_group_name
 
                    )
 
            msg = msg if success else "User wasn't in group"
 
            Session().commit()
 
            return dict(success=success, msg=msg)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'failed to remove member from users group `%s`' % (
 
                'failed to remove member from user group `%s`' % (
 
                        users_group.users_group_name
 
                    )
 
            )
 

	
 
    def get_repo(self, apiuser, repoid):
 
        """"
 
        Get repository by name
 

	
 
        :param apiuser:
 
        :param repoid:
 
        """
 
        repo = get_repo_or_error(repoid)
 
@@ -881,78 +882,78 @@ class ApiController(JSONRPCController):
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'failed to edit permission for user: `%s` in repo: `%s`' % (
 
                    userid, repoid
 
                )
 
            )
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def grant_users_group_permission(self, apiuser, repoid, usersgroupid,
 
                                     perm):
 
        """
 
        Grant permission for users group on given repository, or update
 
        Grant permission for user group on given repository, or update
 
        existing one if found
 

	
 
        :param apiuser:
 
        :param repoid:
 
        :param usersgroupid:
 
        :param perm:
 
        """
 
        repo = get_repo_or_error(repoid)
 
        perm = get_perm_or_error(perm)
 
        users_group = get_users_group_or_error(usersgroupid)
 

	
 
        try:
 
            RepoModel().grant_users_group_permission(repo=repo,
 
                                                     group_name=users_group,
 
                                                     perm=perm)
 

	
 
            Session().commit()
 
            return dict(
 
                msg='Granted perm: `%s` for users group: `%s` in '
 
                msg='Granted perm: `%s` for user group: `%s` in '
 
                    'repo: `%s`' % (
 
                    perm.permission_name, users_group.users_group_name,
 
                    repo.repo_name
 
                ),
 
                success=True
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'failed to edit permission for users group: `%s` in '
 
                'failed to edit permission for user group: `%s` in '
 
                'repo: `%s`' % (
 
                    usersgroupid, repo.repo_name
 
                )
 
            )
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def revoke_users_group_permission(self, apiuser, repoid, usersgroupid):
 
        """
 
        Revoke permission for users group on given repository
 
        Revoke permission for user group on given repository
 

	
 
        :param apiuser:
 
        :param repoid:
 
        :param usersgroupid:
 
        """
 
        repo = get_repo_or_error(repoid)
 
        users_group = get_users_group_or_error(usersgroupid)
 

	
 
        try:
 
            RepoModel().revoke_users_group_permission(repo=repo,
 
                                                      group_name=users_group)
 

	
 
            Session().commit()
 
            return dict(
 
                msg='Revoked perm for users group: `%s` in repo: `%s`' % (
 
                msg='Revoked perm for user group: `%s` in repo: `%s`' % (
 
                    users_group.users_group_name, repo.repo_name
 
                ),
 
                success=True
 
            )
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise JSONRPCError(
 
                'failed to edit permission for users group: `%s` in '
 
                'failed to edit permission for user group: `%s` in '
 
                'repo: `%s`' % (
 
                    users_group.users_group_name, repo.repo_name
 
                )
 
            )
rhodecode/controllers/changeset.py
Show inline comments
 
@@ -320,25 +320,25 @@ class ChangesetController(BaseRepoContro
 
    def changeset_download(self, revision):
 
        return self.index(revision, method='download')
 

	
 
    @jsonify
 
    def comment(self, repo_name, revision):
 
        status = request.POST.get('changeset_status')
 
        change_status = request.POST.get('change_changeset_status')
 
        text = request.POST.get('text')
 
        if status and change_status:
 
            text = text or (_('Status change -> %s')
 
                            % ChangesetStatus.get_status_lbl(status))
 

	
 
        comm = ChangesetCommentsModel().create(
 
        c.co = comm = ChangesetCommentsModel().create(
 
            text=text,
 
            repo=c.rhodecode_db_repo.repo_id,
 
            user=c.rhodecode_user.user_id,
 
            revision=revision,
 
            f_path=request.POST.get('f_path'),
 
            line_no=request.POST.get('line'),
 
            status_change=(ChangesetStatus.get_status_lbl(status)
 
                           if status and change_status else None)
 
        )
 

	
 
        # get status if set !
 
        if status and change_status:
 
@@ -362,30 +362,29 @@ class ChangesetController(BaseRepoContro
 
                h.flash(msg, category='warning')
 
                return redirect(h.url('changeset_home', repo_name=repo_name,
 
                                      revision=revision))
 
        action_logger(self.rhodecode_user,
 
                      'user_commented_revision:%s' % revision,
 
                      c.rhodecode_db_repo, self.ip_addr, self.sa)
 

	
 
        Session().commit()
 

	
 
        if not request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return redirect(h.url('changeset_home', repo_name=repo_name,
 
                                  revision=revision))
 

	
 
        #only ajax below
 
        data = {
 
           'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
 
        }
 
        if comm:
 
            c.co = comm
 
            data.update(comm.get_dict())
 
            data.update({'rendered_text':
 
                         render('changeset/changeset_comment_block.html')})
 

	
 
        return data
 

	
 
    @jsonify
 
    def delete_comment(self, repo_name, comment_id):
 
        co = ChangesetComment.get(comment_id)
 
        owner = co.author.user_id == c.rhodecode_user.user_id
 
        if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner:
 
            ChangesetCommentsModel().delete(comment=co)
rhodecode/controllers/compare.py
Show inline comments
 
@@ -74,41 +74,46 @@ class CompareController(BaseRepoControll
 
            h.flash(h.literal(_('There are no changesets yet')),
 
                    category='warning')
 
            redirect(url('summary_home', repo_name=repo.repo_name))
 

	
 
        except RepositoryError, e:
 
            log.error(traceback.format_exc())
 
            h.flash(str(e), category='warning')
 
            if not partial:
 
                redirect(h.url('summary_home', repo_name=repo.repo_name))
 
            raise HTTPBadRequest()
 

	
 
    def index(self, org_ref_type, org_ref, other_ref_type, other_ref):
 

	
 
        # org_ref will be evaluated in org_repo
 
        org_repo = c.rhodecode_db_repo.repo_name
 
        org_ref = (org_ref_type, org_ref)
 
        # other_ref will be evaluated in other_repo
 
        other_ref = (other_ref_type, other_ref)
 
        other_repo = request.GET.get('other_repo', org_repo)
 
        c.fulldiff = fulldiff = request.GET.get('fulldiff')
 
        # fulldiff disables cut_off_limit
 
        c.fulldiff = request.GET.get('fulldiff')
 
        # only consider this range of changesets
 
        rev_start = request.GET.get('rev_start')
 
        rev_end = request.GET.get('rev_end')
 

	
 
        c.swap_url = h.url('compare_url', as_form=request.GET.get('as_form'),
 
        # partial uses compare_cs.html template directly
 
        partial = request.environ.get('HTTP_X_PARTIAL_XHR')
 
        # as_form puts hidden input field with changeset revisions
 
        c.as_form = partial and request.GET.get('as_form')
 
        # swap url for compare_diff page - never partial and never as_form
 
        c.swap_url = h.url('compare_url',
 
            repo_name=other_repo,
 
            org_ref_type=other_ref[0], org_ref=other_ref[1],
 
            other_repo=org_repo,
 
            other_ref_type=org_ref[0], other_ref=org_ref[1])
 

	
 
        partial = request.environ.get('HTTP_X_PARTIAL_XHR')
 

	
 
        org_repo = Repository.get_by_repo_name(org_repo)
 
        other_repo = Repository.get_by_repo_name(other_repo)
 

	
 
        self.__get_cs_or_redirect(rev=org_ref, repo=org_repo, partial=partial)
 
        self.__get_cs_or_redirect(rev=other_ref, repo=other_repo, partial=partial)
 

	
 
        if org_repo is None:
 
            log.error('Could not find org repo %s' % org_repo)
 
            raise HTTPNotFound
 
        if other_repo is None:
 
            log.error('Could not find other repo %s' % other_repo)
 
            raise HTTPNotFound
 
@@ -139,40 +144,38 @@ class CompareController(BaseRepoControll
 
            _cs = other_repo.scm_instance.get_changeset(rev_start)
 
            rev_start = _cs.parents[0].raw_id if _cs.parents else EmptyChangeset().raw_id
 
            org_ref = ('rev', rev_start)
 
            other_ref = ('rev', rev_end)
 
            #if we cherry pick it's not remote, make the other_repo org_repo
 
            org_repo = other_repo
 

	
 
        c.cs_ranges, ancestor = PullRequestModel().get_compare_data(
 
            org_repo, org_ref, other_repo, other_ref)
 

	
 
        c.statuses = c.rhodecode_db_repo.statuses([x.raw_id for x in
 
                                                   c.cs_ranges])
 
        # defines that we need hidden inputs with changesets
 
        c.as_form = request.GET.get('as_form', False)
 
        if partial:
 
            return render('compare/compare_cs.html')
 

	
 
        if ancestor and org_repo != other_repo:
 
            # case we want a simple diff without incoming changesets,
 
            # previewing what will be merged.
 
            # Make the diff on the forked repo, with
 
            # revision that is common ancestor
 
            log.debug('Using ancestor %s as org_ref instead of %s'
 
                      % (ancestor, org_ref))
 
            org_ref = ('rev', ancestor)
 
            org_repo = other_repo
 

	
 
        diff_limit = self.cut_off_limit if not fulldiff else None
 
        diff_limit = self.cut_off_limit if not c.fulldiff else None
 

	
 
        _diff = diffs.differ(org_repo, org_ref, other_repo, other_ref)
 

	
 
        diff_processor = diffs.DiffProcessor(_diff or '', format='gitdiff',
 
                                             diff_limit=diff_limit)
 
        _parsed = diff_processor.prepare()
 

	
 
        c.limited_diff = False
 
        if isinstance(_parsed, LimitedDiffContainer):
 
            c.limited_diff = True
 

	
 
        c.files = []
rhodecode/controllers/files.py
Show inline comments
 
@@ -477,37 +477,40 @@ class FilesController(BaseRepoController
 
                _url = url('files_annotate_home', repo_name=c.repo_name,
 
                           revision=diff1, f_path=c.f_path)
 
            else:
 
                _url = url('files_home', repo_name=c.repo_name,
 
                           revision=diff1, f_path=c.f_path)
 

	
 
            return redirect(_url)
 
        try:
 
            if diff1 not in ['', None, 'None', '0' * 12, '0' * 40]:
 
                c.changeset_1 = c.rhodecode_repo.get_changeset(diff1)
 
                try:
 
                    node1 = c.changeset_1.get_node(f_path)
 
                    if node1.is_dir():
 
                        raise NodeError('%s path is a %s not a file' % (node1, type(node1)))
 
                except NodeDoesNotExistError:
 
                    c.changeset_1 = EmptyChangeset(cs=diff1,
 
                                                   revision=c.changeset_1.revision,
 
                                                   repo=c.rhodecode_repo)
 
                    node1 = FileNode(f_path, '', changeset=c.changeset_1)
 
            else:
 
                c.changeset_1 = EmptyChangeset(repo=c.rhodecode_repo)
 
                node1 = FileNode(f_path, '', changeset=c.changeset_1)
 

	
 
            if diff2 not in ['', None, 'None', '0' * 12, '0' * 40]:
 
                c.changeset_2 = c.rhodecode_repo.get_changeset(diff2)
 
                try:
 
                    node2 = c.changeset_2.get_node(f_path)
 
                    raise NodeError('%s path is a %s not a file' % (node2, type(node2)))
 
                except NodeDoesNotExistError:
 
                    c.changeset_2 = EmptyChangeset(cs=diff2,
 
                                                   revision=c.changeset_2.revision,
 
                                                   repo=c.rhodecode_repo)
 
                    node2 = FileNode(f_path, '', changeset=c.changeset_2)
 
            else:
 
                c.changeset_2 = EmptyChangeset(repo=c.rhodecode_repo)
 
                node2 = FileNode(f_path, '', changeset=c.changeset_2)
 
        except (RepositoryError, NodeError):
 
            log.error(traceback.format_exc())
 
            return redirect(url('files_home', repo_name=c.repo_name,
 
                                f_path=f_path))
rhodecode/controllers/home.py
Show inline comments
 
@@ -72,16 +72,16 @@ class HomeController(BaseController):
 
        if request.is_xhr:
 
            all_repos = Repository.query().order_by(Repository.repo_name).all()
 
            c.repos_list = self.scm_model.get_repos(all_repos,
 
                                                    sort_key='name_sort',
 
                                                    simple=True)
 
            return render('/repo_switcher_list.html')
 
        else:
 
            raise HTTPBadRequest()
 

	
 
    def branch_tag_switcher(self, repo_name):
 
        if request.is_xhr:
 
            c.rhodecode_db_repo = Repository.get_by_repo_name(c.repo_name)
 
            c.rhodecode_repo = c.rhodecode_db_repo.scm_instance
 
            return render('/switch_to_list.html')
 
        else:
 
            raise HTTPBadRequest()
 
            if c.rhodecode_db_repo:
 
                c.rhodecode_repo = c.rhodecode_db_repo.scm_instance
 
                return render('/switch_to_list.html')
 
        raise HTTPBadRequest()
rhodecode/controllers/pullrequests.py
Show inline comments
 
@@ -58,47 +58,51 @@ log = logging.getLogger(__name__)
 

	
 
class PullrequestsController(BaseRepoController):
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def __before__(self):
 
        super(PullrequestsController, self).__before__()
 
        repo_model = RepoModel()
 
        c.users_array = repo_model.get_users_js()
 
        c.users_groups_array = repo_model.get_users_groups_js()
 

	
 
    def _get_repo_refs(self, repo):
 
        hist_l = []
 

	
 
        branches_group = ([('branch:%s:%s' % (k, v), k) for
 
                         k, v in repo.branches.iteritems()], _("Branches"))
 
        bookmarks_group = ([('book:%s:%s' % (k, v), k) for
 
                         k, v in repo.bookmarks.iteritems()], _("Bookmarks"))
 
        tags_group = ([('tag:%s:%s' % (k, v), k) for
 
                         k, v in repo.tags.iteritems()
 
                         if k != 'tip'], _("Tags"))
 
    def _get_repo_refs(self, repo, rev=None):
 
        """return a structure with repo's interesting changesets, suitable for
 
        the selectors in pullrequest.html"""
 
        branches = [('branch:%s:%s' % (k, v), k)
 
                    for k, v in repo.branches.iteritems()]
 
        bookmarks = [('book:%s:%s' % (k, v), k)
 
                     for k, v in repo.bookmarks.iteritems()]
 
        tags = [('tag:%s:%s' % (k, v), k)
 
                for k, v in repo.tags.iteritems()
 
                if k != 'tip']
 

	
 
        tip = repo.tags['tip']
 
        tipref = 'tag:tip:%s' % tip
 
        colontip = ':' + tip
 
        tips = [x[1] for x in branches_group[0] + bookmarks_group[0] + tags_group[0]
 
        tips = [x[1] for x in branches + bookmarks + tags
 
                if x[0].endswith(colontip)]
 
        tags_group[0].append((tipref, 'tip (%s)' % ', '.join(tips)))
 
        selected = 'tag:tip:%s' % tip
 
        special = [(selected, 'tip (%s)' % ', '.join(tips))]
 

	
 
        hist_l.append(bookmarks_group)
 
        hist_l.append(branches_group)
 
        hist_l.append(tags_group)
 
        if rev:
 
            selected = 'rev:%s:%s' % (rev, rev)
 
            special.append((selected, rev))
 

	
 
        return hist_l, tipref
 
        return [(special, _("Special")),
 
                (bookmarks, _("Bookmarks")),
 
                (branches, _("Branches")),
 
                (tags, _("Tags")),
 
                ], selected
 

	
 
    def _get_is_allowed_change_status(self, pull_request):
 
        owner = self.rhodecode_user.user_id == pull_request.user_id
 
        reviewer = self.rhodecode_user.user_id in [x.user_id for x in
 
                                                   pull_request.reviewers]
 
        return (self.rhodecode_user.admin or owner or reviewer)
 

	
 
    def show_all(self, repo_name):
 
        c.pull_requests = PullRequestModel().get_all(repo_name)
 
        c.repo_name = repo_name
 
        return render('/pullrequests/pullrequest_show_all.html')
 

	
 
@@ -282,26 +286,24 @@ class PullrequestsController(BaseRepoCon
 
        c.org_repo = org_repo
 
        c.other_repo = other_repo
 

	
 
        c.fulldiff = fulldiff = request.GET.get('fulldiff')
 

	
 
        c.cs_ranges = [org_repo.get_changeset(x) for x in pull_request.revisions]
 

	
 
        other_ref = ('rev', getattr(c.cs_ranges[0].parents[0]
 
                                  if c.cs_ranges[0].parents
 
                                  else EmptyChangeset(), 'raw_id'))
 

	
 
        c.statuses = org_repo.statuses([x.raw_id for x in c.cs_ranges])
 
        # defines that we need hidden inputs with changesets
 
        c.as_form = request.GET.get('as_form', False)
 

	
 
        c.org_ref = org_ref[1]
 
        c.org_ref_type = org_ref[0]
 
        c.other_ref = other_ref[1]
 
        c.other_ref_type = other_ref[0]
 

	
 
        diff_limit = self.cut_off_limit if not fulldiff else None
 

	
 
        #we swap org/other ref since we run a simple diff on one repo
 
        _diff = diffs.differ(org_repo, other_ref, other_repo, org_ref)
 

	
 
        diff_processor = diffs.DiffProcessor(_diff or '', format='gitdiff',
 
@@ -382,68 +384,75 @@ class PullrequestsController(BaseRepoCon
 
        except:
 
            log.error(traceback.format_exc())
 
            cur_status = 'undefined'
 
        if c.pull_request.is_closed() and 0:
 
            c.current_changeset_status = cur_status
 
        else:
 
            # changeset(pull-request) status calulation based on reviewers
 
            c.current_changeset_status = cs_model.calculate_status(
 
                                            c.pull_request_reviewers,
 
                                         )
 
        c.changeset_statuses = ChangesetStatus.STATUSES
 

	
 
        c.as_form = False
 
        return render('/pullrequests/pullrequest_show.html')
 

	
 
    @NotAnonymous()
 
    @jsonify
 
    def comment(self, repo_name, pull_request_id):
 
        pull_request = PullRequest.get_or_404(pull_request_id)
 
        if pull_request.is_closed():
 
            raise HTTPForbidden()
 

	
 
        status = request.POST.get('changeset_status')
 
        change_status = request.POST.get('change_changeset_status')
 
        text = request.POST.get('text')
 
        close_pr = request.POST.get('save_close')
 

	
 
        allowed_to_change_status = self._get_is_allowed_change_status(pull_request)
 
        if status and change_status and allowed_to_change_status:
 
            text = text or (_('Status change -> %s')
 
            _def = (_('status change -> %s')
 
                            % ChangesetStatus.get_status_lbl(status))
 
            if close_pr:
 
                _def = _('Closing with') + ' ' + _def
 
            text = text or _def
 
        comm = ChangesetCommentsModel().create(
 
            text=text,
 
            repo=c.rhodecode_db_repo.repo_id,
 
            user=c.rhodecode_user.user_id,
 
            pull_request=pull_request_id,
 
            f_path=request.POST.get('f_path'),
 
            line_no=request.POST.get('line'),
 
            status_change=(ChangesetStatus.get_status_lbl(status)
 
            if status and change_status and allowed_to_change_status else None)
 
                           if status and change_status
 
                           and allowed_to_change_status else None),
 
            closing_pr=close_pr
 
        )
 

	
 
        action_logger(self.rhodecode_user,
 
                      'user_commented_pull_request:%s' % pull_request_id,
 
                      c.rhodecode_db_repo, self.ip_addr, self.sa)
 

	
 
        if allowed_to_change_status:
 
            # get status if set !
 
            if status and change_status:
 
                ChangesetStatusModel().set_status(
 
                    c.rhodecode_db_repo.repo_id,
 
                    status,
 
                    c.rhodecode_user.user_id,
 
                    comm,
 
                    pull_request=pull_request_id
 
                )
 

	
 
            if request.POST.get('save_close'):
 
            if close_pr:
 
                if status in ['rejected', 'approved']:
 
                    PullRequestModel().close_pull_request(pull_request_id)
 
                    action_logger(self.rhodecode_user,
 
                              'user_closed_pull_request:%s' % pull_request_id,
 
                              c.rhodecode_db_repo, self.ip_addr, self.sa)
 
                else:
 
                    h.flash(_('Closing pull request on other statuses than '
 
                              'rejected or approved forbidden'),
 
                            category='warning')
 

	
 
        Session().commit()
 

	
rhodecode/lib/auth.py
Show inline comments
 
@@ -402,25 +402,25 @@ class  AuthUser(object):
 

	
 
    @property
 
    def repos_admin(self):
 
        """
 
        Returns list of repositories you're an admin of
 
        """
 
        return [x[0] for x in self.permissions['repositories'].iteritems()
 
                if x[1] == 'repository.admin']
 

	
 
    @property
 
    def groups_admin(self):
 
        """
 
        Returns list of repositories groups you're an admin of
 
        Returns list of repository groups you're an admin of
 
        """
 
        return [x[0] for x in self.permissions['repositories_groups'].iteritems()
 
                if x[1] == 'group.admin']
 

	
 
    @property
 
    def ip_allowed(self):
 
        """
 
        Checks if ip_addr used in constructor is allowed from defined list of
 
        allowed ip_addresses for user
 

	
 
        :returns: boolean, True if ip is in allowed ip range
 
        """
rhodecode/lib/celerylib/__init__.py
Show inline comments
 
@@ -59,24 +59,26 @@ class ResultWrapper(object):
 

	
 

	
 
def run_task(task, *args, **kwargs):
 
    if CELERY_ON:
 
        try:
 
            t = task.apply_async(args=args, kwargs=kwargs)
 
            log.info('running task %s:%s' % (t.task_id, task))
 
            return t
 

	
 
        except socket.error, e:
 
            if isinstance(e, IOError) and e.errno == 111:
 
                log.debug('Unable to connect to celeryd. Sync execution')
 
                global CELERY_ON
 
                CELERY_ON = False
 
            else:
 
                log.error(traceback.format_exc())
 
        except KeyError, e:
 
                log.debug('Unable to connect to celeryd. Sync execution')
 
        except Exception, e:
 
            log.error(traceback.format_exc())
 

	
 
    log.debug('executing task %s in sync mode' % task)
 
    return ResultWrapper(task(*args, **kwargs))
 

	
 

	
 
def __get_lockkey(func, *fargs, **fkwargs):
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -242,94 +242,28 @@ def get_commits_stats(repo_name, ts_min_
 
        # execute another task if celery is enabled
 
        if len(repo.revisions) > 1 and CELERY_ON and recurse_limit > 0:
 
            recurse_limit -= 1
 
            run_task(get_commits_stats, repo_name, ts_min_y, ts_max_y,
 
                     recurse_limit)
 
        if recurse_limit <= 0:
 
            log.debug('Breaking recursive mode due to reach of recurse limit')
 
        return True
 
    except LockHeld:
 
        log.info('LockHeld')
 
        return 'Task with key %s already running' % lockkey
 

	
 
@task(ignore_result=True)
 
@dbsession
 
def send_password_link(user_email):
 
    from rhodecode.model.notification import EmailNotificationModel
 

	
 
    log = get_logger(send_password_link)
 
    DBS = get_session()
 

	
 
    try:
 
        user = User.get_by_email(user_email)
 
        if user:
 
            log.debug('password reset user found %s' % user)
 
            link = url('reset_password_confirmation', key=user.api_key,
 
                       qualified=True)
 
            reg_type = EmailNotificationModel.TYPE_PASSWORD_RESET
 
            body = EmailNotificationModel().get_email_tmpl(reg_type,
 
                                                **{'user':user.short_contact,
 
                                                   'reset_url':link})
 
            log.debug('sending email')
 
            run_task(send_email, user_email,
 
                     _("password reset link"), body)
 
            log.info('send new password mail to %s' % user_email)
 
        else:
 
            log.debug("password reset email %s not found" % user_email)
 
    except:
 
        log.error(traceback.format_exc())
 
        return False
 

	
 
    return True
 

	
 
@task(ignore_result=True)
 
@dbsession
 
def reset_user_password(user_email):
 
    from rhodecode.lib import auth
 

	
 
    log = get_logger(reset_user_password)
 
    DBS = get_session()
 

	
 
    try:
 
        try:
 
            user = User.get_by_email(user_email)
 
            new_passwd = auth.PasswordGenerator().gen_password(8,
 
                             auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
 
            if user:
 
                user.password = auth.get_crypt_password(new_passwd)
 
                user.api_key = auth.generate_api_key(user.username)
 
                DBS.add(user)
 
                DBS.commit()
 
                log.info('change password for %s' % user_email)
 
            if new_passwd is None:
 
                raise Exception('unable to generate new password')
 
        except:
 
            log.error(traceback.format_exc())
 
            DBS.rollback()
 

	
 
        run_task(send_email, user_email,
 
                 'Your new password',
 
                 'Your new RhodeCode password:%s' % (new_passwd))
 
        log.info('send new password mail to %s' % user_email)
 

	
 
    except:
 
        log.error('Failed to update user password')
 
        log.error(traceback.format_exc())
 

	
 
    return True
 

	
 

	
 
@task(ignore_result=True)
 
@dbsession
 
def send_email(recipients, subject, body, html_body=''):
 
def send_email(recipients, subject, body='', html_body=''):
 
    """
 
    Sends an email with defined parameters from the .ini files.
 

	
 
    :param recipients: list of recipients, it this is empty the defined email
 
        address from field 'email_to' is used instead
 
    :param subject: subject of the mail
 
    :param body: body of the mail
 
    :param html_body: html version of body
 
    """
 
    log = get_logger(send_email)
 
    DBS = get_session()
 

	
 
@@ -339,25 +273,25 @@ def send_email(recipients, subject, body
 
        # if recipients are not defined we send to email_config + all admins
 
        admins = [u.email for u in User.query()
 
                  .filter(User.admin == True).all()]
 
        recipients = [email_config.get('email_to')] + admins
 

	
 
    mail_from = email_config.get('app_email_from', 'RhodeCode')
 
    user = email_config.get('smtp_username')
 
    passwd = email_config.get('smtp_password')
 
    mail_server = email_config.get('smtp_server')
 
    mail_port = email_config.get('smtp_port')
 
    tls = str2bool(email_config.get('smtp_use_tls'))
 
    ssl = str2bool(email_config.get('smtp_use_ssl'))
 
    debug = str2bool(config.get('debug'))
 
    debug = str2bool(email_config.get('debug'))
 
    smtp_auth = email_config.get('smtp_auth')
 

	
 
    if not mail_server:
 
        log.error("SMTP mail server not configured - cannot send mail")
 
        return False
 

	
 
    try:
 
        m = SmtpMailer(mail_from, user, passwd, mail_server, smtp_auth,
 
                       mail_port, ssl, tls, debug=debug)
 
        m.send(recipients, subject, body, html_body)
 
    except:
 
        log.error('Mail sending failed')
rhodecode/lib/dbmigrate/schema/db_1_2_0.py
Show inline comments
 
@@ -32,25 +32,25 @@ from datetime import date
 
from sqlalchemy import *
 
from sqlalchemy.ext.hybrid import hybrid_property
 
from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
 
from beaker.cache import cache_region, region_invalidate
 

	
 
from rhodecode.lib.vcs import get_backend
 
from rhodecode.lib.vcs.utils.helpers import get_scm
 
from rhodecode.lib.vcs.exceptions import VCSError
 
from rhodecode.lib.vcs.utils.lazy import LazyProperty
 

	
 
from rhodecode.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
 
    generate_api_key, safe_unicode
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 
from rhodecode.lib.exceptions import UserGroupsAssignedException
 
from rhodecode.lib.compat import json
 

	
 
from rhodecode.model.meta import Base, Session
 
from rhodecode.lib.caching_query import FromCache
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 
#==============================================================================
 
# BASE CLASSES
 
#==============================================================================
 

	
 
@@ -273,25 +273,25 @@ class User(Base, BaseModel):
 
    email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
 
    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    user_log = relationship('UserLog', cascade='all')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 
    group_member = relationship('UserGroupMember', cascade='all')
 

	
 
    @property
 
    def full_contact(self):
 
        return '%s %s <%s>' % (self.name, self.lastname, self.email)
 

	
 
    @property
 
    def short_contact(self):
 
        return '%s %s' % (self.name, self.lastname)
 

	
 
    @property
 
    def is_admin(self):
 
        return self.admin
 
@@ -352,33 +352,33 @@ class UserLog(Base, BaseModel):
 
    user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
 

	
 
    @property
 
    def action_as_day(self):
 
        return date(*self.action_date.timetuple()[:3])
 

	
 
    user = relationship('User')
 
    repository = relationship('Repository')
 

	
 

	
 
class UsersGroup(Base, BaseModel):
 
class UserGroup(Base, BaseModel):
 
    __tablename__ = 'users_groups'
 
    __table_args__ = {'extend_existing':True}
 

	
 
    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
 

	
 
    members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 

	
 
    def __repr__(self):
 
        return '<userGroup(%s)>' % (self.users_group_name)
 

	
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
 
        if case_insensitive:
 
            gr = cls.query()\
 
                .filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            gr = cls.query()\
 
                .filter(cls.users_group_name == group_name)
 
@@ -416,75 +416,75 @@ class UsersGroup(Base, BaseModel):
 

	
 
        try:
 
            users_group = cls.get(users_group_id, cache=False)
 

	
 
            for k, v in form_data.items():
 
                if k == 'users_group_members':
 
                    users_group.members = []
 
                    Session.flush()
 
                    members_list = []
 
                    if v:
 
                        v = [v] if isinstance(v, basestring) else v
 
                        for u_id in set(v):
 
                            member = UsersGroupMember(users_group_id, u_id)
 
                            member = UserGroupMember(users_group_id, u_id)
 
                            members_list.append(member)
 
                    setattr(users_group, 'members', members_list)
 
                setattr(users_group, k, v)
 

	
 
            Session.add(users_group)
 
            Session.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            raise
 

	
 
    @classmethod
 
    def delete(cls, users_group_id):
 
        try:
 

	
 
            # check if this group is not assigned to repo
 
            assigned_groups = UsersGroupRepoToPerm.query()\
 
                .filter(UsersGroupRepoToPerm.users_group_id ==
 
            assigned_groups = UserGroupRepoToPerm.query()\
 
                .filter(UserGroupRepoToPerm.users_group_id ==
 
                        users_group_id).all()
 

	
 
            if assigned_groups:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                raise UserGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 

	
 
            users_group = cls.get(users_group_id, cache=False)
 
            Session.delete(users_group)
 
            Session.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            raise
 

	
 
class UsersGroupMember(Base, BaseModel):
 
class UserGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = {'extend_existing':True}
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 
    @staticmethod
 
    def add_user_to_group(group, user):
 
        ugm = UsersGroupMember()
 
        ugm = UserGroupMember()
 
        ugm.users_group = group
 
        ugm.user = user
 
        Session.add(ugm)
 
        Session.commit()
 
        return ugm
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
 

	
 
    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
@@ -496,25 +496,25 @@ class Repository(Base, BaseModel):
 
    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
 
    description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
 

	
 
    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
 

	
 

	
 
    user = relationship('User')
 
    fork = relationship('Repository', remote_side=repo_id)
 
    group = relationship('RepoGroup')
 
    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 
    stats = relationship('Statistics', cascade='all', uselist=False)
 

	
 
    followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
 

	
 
    logs = relationship('UserLog', cascade='all')
 

	
 
    def __repr__(self):
 
        return "<%s('%s:%s')>" % (self.__class__.__name__,
 
                                  self.repo_id, self.repo_name)
 

	
 
    @classmethod
 
    def url_sep(cls):
 
@@ -900,47 +900,47 @@ class UserToPerm(Base, BaseModel):
 
    @classmethod
 
    def revoke_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            cls.query().filter(cls.user_id == user_id)\
 
                .filter(cls.permission == perm).delete()
 
            Session.commit()
 
        except:
 
            Session.rollback()
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
class UserGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), {'extend_existing':True})
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    def __repr__(self):
 
        return '<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
class UserGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_to_perm'
 
    __table_args__ = {'extend_existing':True}
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
    @classmethod
 
    def has_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        return cls.query().filter(cls.users_group_id ==
 
                                         users_group_id)\
 
                                         .filter(cls.permission == perm)\
 
                                         .scalar() is not None
rhodecode/lib/dbmigrate/schema/db_1_3_0.py
Show inline comments
 
@@ -296,25 +296,25 @@ class User(Base, BaseModel):
 
    last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
 
    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    user_log = relationship('UserLog', cascade='all')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 
    group_member = relationship('UserGroupMember', cascade='all')
 

	
 
    notifications = relationship('UserNotification', cascade='all')
 
    # notifications assigned to this user
 
    user_created_notifications = relationship('Notification', cascade='all')
 
    # comments created by this user
 
    user_comments = relationship('ChangesetComment', cascade='all')
 

	
 
    @hybrid_property
 
    def email(self):
 
        return self._email
 

	
 
    @email.setter
 
@@ -414,38 +414,38 @@ class UserLog(Base, BaseModel):
 
    user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
 

	
 
    @property
 
    def action_as_day(self):
 
        return datetime.date(*self.action_date.timetuple()[:3])
 

	
 
    user = relationship('User')
 
    repository = relationship('Repository', cascade='')
 

	
 

	
 
class UsersGroup(Base, BaseModel):
 
class UserGroup(Base, BaseModel):
 
    __tablename__ = 'users_groups'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
 

	
 
    members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UsersGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 

	
 
    def __unicode__(self):
 
        return u'<userGroup(%s)>' % (self.users_group_name)
 

	
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False,
 
                          case_insensitive=False):
 
        if case_insensitive:
 
            q = cls.query().filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            q = cls.query().filter(cls.users_group_name == group_name)
 
        if cache:
 
@@ -456,37 +456,37 @@ class UsersGroup(Base, BaseModel):
 
            )
 
        return q.scalar()
 

	
 
    @classmethod
 
    def get(cls, users_group_id, cache=False):
 
        users_group = cls.query()
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                    "get_users_group_%s" % users_group_id))
 
        return users_group.get(users_group_id)
 

	
 

	
 
class UsersGroupMember(Base, BaseModel):
 
class UserGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (
 
        UniqueConstraint('repo_name'),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'},
 
@@ -501,25 +501,25 @@ class Repository(Base, BaseModel):
 
    enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
 
    enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
 
    description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
 

	
 
    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
 

	
 
    user = relationship('User')
 
    fork = relationship('Repository', remote_side=repo_id)
 
    group = relationship('RepoGroup')
 
    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 
    stats = relationship('Statistics', cascade='all', uselist=False)
 

	
 
    followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
 

	
 
    logs = relationship('UserLog')
 

	
 
    def __unicode__(self):
 
        return u"<%s('%s:%s')>" % (self.__class__.__name__,self.repo_id,
 
                                   self.repo_name)
 

	
 
    @classmethod
 
    def url_sep(cls):
 
@@ -740,25 +740,25 @@ class RepoGroup(Base, BaseModel):
 
        CheckConstraint('group_id != group_parent_id'),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 
    __mapper_args__ = {'order_by': 'group_name'}
 

	
 
    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
 
    group_description = Column("group_description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoGroupToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
 

	
 
    parent_group = relationship('RepoGroup', remote_side=group_id)
 

	
 
    def __init__(self, group_name='', parent_group=None):
 
        self.group_name = group_name
 
        self.parent_group = parent_group
 

	
 
    def __unicode__(self):
 
        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
 
                                  self.group_name)
 

	
 
    @classmethod
 
@@ -937,100 +937,100 @@ class UserToPerm(Base, BaseModel):
 
        UniqueConstraint('user_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission', lazy='joined')
 

	
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
class UserGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    @classmethod
 
    def create(cls, users_group, repository, permission):
 
        n = cls()
 
        n.users_group = users_group
 
        n.repository = repository
 
        n.permission = permission
 
        Session.add(n)
 
        return n
 

	
 
    def __unicode__(self):
 
        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
class UserGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'permission_id',),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'user_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('user_id', 'group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    group = relationship('RepoGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UsersGroupRepoGroupToPerm(Base, BaseModel):
 
class UserGroupRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'group_id'),
 
        {'extend_existing': True, 'mysql_engine':'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    group = relationship('RepoGroup')
 

	
 

	
 
class Statistics(Base, BaseModel):
 
    __tablename__ = 'statistics'
 
    __table_args__ = (
 
         UniqueConstraint('repository_id'),
 
         {'extend_existing': True, 'mysql_engine':'InnoDB',
 
          'mysql_charset': 'utf8'}
 
    )
 
    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
rhodecode/lib/dbmigrate/schema/db_1_4_0.py
Show inline comments
 
@@ -313,25 +313,25 @@ class User(Base, BaseModel):
 
    ldap_dn = Column("ldap_dn", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    api_key = Column("api_key", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    user_log = relationship('UserLog', cascade='all')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 
    group_member = relationship('UserGroupMember', cascade='all')
 

	
 
    notifications = relationship('UserNotification', cascade='all')
 
    # notifications assigned to this user
 
    user_created_notifications = relationship('Notification', cascade='all')
 
    # comments created by this user
 
    user_comments = relationship('ChangesetComment', cascade='all')
 
    #extra emails for this user
 
    user_emails = relationship('UserEmailMap', cascade='all')
 

	
 
    @hybrid_property
 
    def email(self):
 
        return self._email
 
@@ -512,39 +512,39 @@ class UserLog(Base, BaseModel):
 
    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
 

	
 
    @property
 
    def action_as_day(self):
 
        return datetime.date(*self.action_date.timetuple()[:3])
 

	
 
    user = relationship('User')
 
    repository = relationship('Repository', cascade='')
 

	
 

	
 
class UsersGroup(Base, BaseModel):
 
class UserGroup(Base, BaseModel):
 
    __tablename__ = 'users_groups'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
 
    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UsersGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 

	
 
    def __unicode__(self):
 
        return u'<userGroup(%s)>' % (self.users_group_name)
 

	
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False,
 
                          case_insensitive=False):
 
        if case_insensitive:
 
            q = cls.query().filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            q = cls.query().filter(cls.users_group_name == group_name)
 
        if cache:
 
@@ -566,37 +566,37 @@ class UsersGroup(Base, BaseModel):
 
    def get_api_data(self):
 
        users_group = self
 

	
 
        data = dict(
 
            users_group_id=users_group.users_group_id,
 
            group_name=users_group.users_group_name,
 
            active=users_group.users_group_active,
 
        )
 

	
 
        return data
 

	
 

	
 
class UsersGroupMember(Base, BaseModel):
 
class UserGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (
 
        UniqueConstraint('repo_name'),
 
        Index('r_repo_name_idx', 'repo_name'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
@@ -616,25 +616,25 @@ class Repository(Base, BaseModel):
 
    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
 
    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 
    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
 

	
 
    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
 

	
 
    user = relationship('User')
 
    fork = relationship('Repository', remote_side=repo_id)
 
    group = relationship('RepoGroup')
 
    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 
    stats = relationship('Statistics', cascade='all', uselist=False)
 

	
 
    followers = relationship('UserFollowing',
 
                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
 
                             cascade='all')
 

	
 
    logs = relationship('UserLog')
 
    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
 

	
 
    pull_requests_org = relationship('PullRequest',
 
                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
 
                    cascade="all, delete, delete-orphan")
 
@@ -1004,25 +1004,25 @@ class RepoGroup(Base, BaseModel):
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 
    __mapper_args__ = {'order_by': 'group_name'}
 

	
 
    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
 
    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 

	
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoGroupToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
 

	
 
    parent_group = relationship('RepoGroup', remote_side=group_id)
 

	
 
    def __init__(self, group_name='', parent_group=None):
 
        self.group_name = group_name
 
        self.parent_group = parent_group
 

	
 
    def __unicode__(self):
 
        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
 
                                  self.group_name)
 

	
 
    @classmethod
 
@@ -1268,100 +1268,100 @@ class UserToPerm(Base, BaseModel):
 
        UniqueConstraint('user_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission', lazy='joined')
 

	
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
class UserGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    @classmethod
 
    def create(cls, users_group, repository, permission):
 
        n = cls()
 
        n.users_group = users_group
 
        n.repository = repository
 
        n.permission = permission
 
        Session().add(n)
 
        return n
 

	
 
    def __unicode__(self):
 
        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
class UserGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'permission_id',),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'user_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('user_id', 'group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    group = relationship('RepoGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UsersGroupRepoGroupToPerm(Base, BaseModel):
 
class UserGroupRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'group_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    group = relationship('RepoGroup')
 

	
 

	
 
class Statistics(Base, BaseModel):
 
    __tablename__ = 'statistics'
 
    __table_args__ = (
 
         UniqueConstraint('repository_id'),
 
         {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
          'mysql_charset': 'utf8'}
 
    )
 
    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
rhodecode/lib/dbmigrate/schema/db_1_5_0.py
Show inline comments
 
@@ -332,25 +332,25 @@ class User(Base, BaseModel):
 
    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    user_log = relationship('UserLog')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
 

	
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 
    group_member = relationship('UserGroupMember', cascade='all')
 

	
 
    notifications = relationship('UserNotification', cascade='all')
 
    # notifications assigned to this user
 
    user_created_notifications = relationship('Notification', cascade='all')
 
    # comments created by this user
 
    user_comments = relationship('ChangesetComment', cascade='all')
 
    #extra emails for this user
 
    user_emails = relationship('UserEmailMap', cascade='all')
 

	
 
    @hybrid_property
 
    def email(self):
 
        return self._email
 
@@ -532,39 +532,39 @@ class UserLog(Base, BaseModel):
 
    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
 

	
 
    @property
 
    def action_as_day(self):
 
        return datetime.date(*self.action_date.timetuple()[:3])
 

	
 
    user = relationship('User')
 
    repository = relationship('Repository', cascade='')
 

	
 

	
 
class UsersGroup(Base, BaseModel):
 
class UserGroup(Base, BaseModel):
 
    __tablename__ = 'users_groups'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
 
    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UsersGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 

	
 
    def __unicode__(self):
 
        return u'<userGroup(%s)>' % (self.users_group_name)
 

	
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False,
 
                          case_insensitive=False):
 
        if case_insensitive:
 
            q = cls.query().filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            q = cls.query().filter(cls.users_group_name == group_name)
 
        if cache:
 
@@ -586,37 +586,37 @@ class UsersGroup(Base, BaseModel):
 
    def get_api_data(self):
 
        users_group = self
 

	
 
        data = dict(
 
            users_group_id=users_group.users_group_id,
 
            group_name=users_group.users_group_name,
 
            active=users_group.users_group_active,
 
        )
 

	
 
        return data
 

	
 

	
 
class UsersGroupMember(Base, BaseModel):
 
class UserGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (
 
        UniqueConstraint('repo_name'),
 
        Index('r_repo_name_idx', 'repo_name'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
@@ -636,25 +636,25 @@ class Repository(Base, BaseModel):
 
    updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
 
    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 
    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
 

	
 
    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
 

	
 
    user = relationship('User')
 
    fork = relationship('Repository', remote_side=repo_id)
 
    group = relationship('RepoGroup')
 
    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 
    stats = relationship('Statistics', cascade='all', uselist=False)
 

	
 
    followers = relationship('UserFollowing',
 
                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
 
                             cascade='all')
 

	
 
    logs = relationship('UserLog')
 
    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
 

	
 
    pull_requests_org = relationship('PullRequest',
 
                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
 
                    cascade="all, delete, delete-orphan")
 
@@ -1024,25 +1024,25 @@ class RepoGroup(Base, BaseModel):
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 
    __mapper_args__ = {'order_by': 'group_name'}
 

	
 
    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
 
    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 

	
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoGroupToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
 

	
 
    parent_group = relationship('RepoGroup', remote_side=group_id)
 

	
 
    def __init__(self, group_name='', parent_group=None):
 
        self.group_name = group_name
 
        self.parent_group = parent_group
 

	
 
    def __unicode__(self):
 
        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
 
                                  self.group_name)
 

	
 
    @classmethod
 
@@ -1288,100 +1288,100 @@ class UserToPerm(Base, BaseModel):
 
        UniqueConstraint('user_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission', lazy='joined')
 

	
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
class UserGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    @classmethod
 
    def create(cls, users_group, repository, permission):
 
        n = cls()
 
        n.users_group = users_group
 
        n.repository = repository
 
        n.permission = permission
 
        Session().add(n)
 
        return n
 

	
 
    def __unicode__(self):
 
        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
class UserGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'permission_id',),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'user_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('user_id', 'group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    group = relationship('RepoGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UsersGroupRepoGroupToPerm(Base, BaseModel):
 
class UserGroupRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'group_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    group = relationship('RepoGroup')
 

	
 

	
 
class Statistics(Base, BaseModel):
 
    __tablename__ = 'statistics'
 
    __table_args__ = (
 
         UniqueConstraint('repository_id'),
 
         {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
          'mysql_charset': 'utf8'}
 
    )
 
    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
rhodecode/lib/dbmigrate/schema/db_1_5_2.py
Show inline comments
 
@@ -332,25 +332,25 @@ class User(Base, BaseModel):
 
    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    user_log = relationship('UserLog')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
 

	
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 
    group_member = relationship('UserGroupMember', cascade='all')
 

	
 
    notifications = relationship('UserNotification', cascade='all')
 
    # notifications assigned to this user
 
    user_created_notifications = relationship('Notification', cascade='all')
 
    # comments created by this user
 
    user_comments = relationship('ChangesetComment', cascade='all')
 
    #extra emails for this user
 
    user_emails = relationship('UserEmailMap', cascade='all')
 

	
 
    @hybrid_property
 
    def email(self):
 
        return self._email
 
@@ -566,39 +566,39 @@ class UserLog(Base, BaseModel):
 
    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
 

	
 
    @property
 
    def action_as_day(self):
 
        return datetime.date(*self.action_date.timetuple()[:3])
 

	
 
    user = relationship('User')
 
    repository = relationship('Repository', cascade='')
 

	
 

	
 
class UsersGroup(Base, BaseModel):
 
class UserGroup(Base, BaseModel):
 
    __tablename__ = 'users_groups'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
 
    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UsersGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 

	
 
    def __unicode__(self):
 
        return u'<userGroup(%s)>' % (self.users_group_name)
 

	
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False,
 
                          case_insensitive=False):
 
        if case_insensitive:
 
            q = cls.query().filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            q = cls.query().filter(cls.users_group_name == group_name)
 
        if cache:
 
@@ -620,37 +620,37 @@ class UsersGroup(Base, BaseModel):
 
    def get_api_data(self):
 
        users_group = self
 

	
 
        data = dict(
 
            users_group_id=users_group.users_group_id,
 
            group_name=users_group.users_group_name,
 
            active=users_group.users_group_active,
 
        )
 

	
 
        return data
 

	
 

	
 
class UsersGroupMember(Base, BaseModel):
 
class UserGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (
 
        UniqueConstraint('repo_name'),
 
        Index('r_repo_name_idx', 'repo_name'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
@@ -671,25 +671,25 @@ class Repository(Base, BaseModel):
 
    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 
    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
 
    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
 

	
 
    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
 

	
 
    user = relationship('User')
 
    fork = relationship('Repository', remote_side=repo_id)
 
    group = relationship('RepoGroup')
 
    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 
    stats = relationship('Statistics', cascade='all', uselist=False)
 

	
 
    followers = relationship('UserFollowing',
 
                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
 
                             cascade='all')
 

	
 
    logs = relationship('UserLog')
 
    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
 

	
 
    pull_requests_org = relationship('PullRequest',
 
                    primaryjoin='PullRequest.org_repo_id==Repository.repo_id',
 
                    cascade="all, delete, delete-orphan")
 
@@ -1130,25 +1130,25 @@ class RepoGroup(Base, BaseModel):
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 
    __mapper_args__ = {'order_by': 'group_name'}
 

	
 
    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
 
    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 

	
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoGroupToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
 

	
 
    parent_group = relationship('RepoGroup', remote_side=group_id)
 

	
 
    def __init__(self, group_name='', parent_group=None):
 
        self.group_name = group_name
 
        self.parent_group = parent_group
 

	
 
    def __unicode__(self):
 
        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
 
                                  self.group_name)
 

	
 
    @classmethod
 
@@ -1394,100 +1394,100 @@ class UserToPerm(Base, BaseModel):
 
        UniqueConstraint('user_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission', lazy='joined')
 

	
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
class UserGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    @classmethod
 
    def create(cls, users_group, repository, permission):
 
        n = cls()
 
        n.users_group = users_group
 
        n.repository = repository
 
        n.permission = permission
 
        Session().add(n)
 
        return n
 

	
 
    def __unicode__(self):
 
        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
class UserGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'permission_id',),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'user_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('user_id', 'group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    group = relationship('RepoGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UsersGroupRepoGroupToPerm(Base, BaseModel):
 
class UserGroupRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'group_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    group = relationship('RepoGroup')
 

	
 

	
 
class Statistics(Base, BaseModel):
 
    __tablename__ = 'statistics'
 
    __table_args__ = (
 
         UniqueConstraint('repository_id'),
 
         {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
          'mysql_charset': 'utf8'}
 
    )
 
    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
rhodecode/lib/dbmigrate/versions/003_version_1_2_0.py
Show inline comments
 
@@ -25,44 +25,44 @@ def upgrade(migrate_engine):
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import Group as Group
 
    Group().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `group_to_perm`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UserRepoGroupToPerm
 
    UserRepoGroupToPerm().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `users_groups`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UsersGroup
 
    UsersGroup().__table__.create()
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UserGroup
 
    UserGroup().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `users_groups_members`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UsersGroupMember
 
    UsersGroupMember().__table__.create()
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UserGroupMember
 
    UserGroupMember().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `users_group_repo_to_perm`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UsersGroupRepoToPerm
 
    UsersGroupRepoToPerm().__table__.create()
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UserGroupRepoToPerm
 
    UserGroupRepoToPerm().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `users_group_to_perm`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UsersGroupToPerm
 
    UsersGroupToPerm().__table__.create()
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import UserGroupToPerm
 
    UserGroupToPerm().__table__.create()
 

	
 
    #==========================================================================
 
    # Upgrade of `users` table
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_2_0 import User
 

	
 
    #add column
 
    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    ldap_dn.create(User().__table__)
 

	
 
    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    api_key.create(User().__table__)
rhodecode/lib/dbmigrate/versions/004_version_1_3_0.py
Show inline comments
 
@@ -12,50 +12,50 @@ from rhodecode.lib.dbmigrate.migrate.cha
 
from rhodecode.model.meta import Base
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def upgrade(migrate_engine):
 
    """ Upgrade operations go here.
 
    Don't create your own engine; bind migrate_engine to your metadata
 
    """
 
    #==========================================================================
 
    # Add table `users_group_repo_group_to_perm`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UsersGroupRepoGroupToPerm
 
    UsersGroupRepoGroupToPerm().__table__.create()
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UserGroupRepoGroupToPerm
 
    UserGroupRepoGroupToPerm().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `changeset_comments`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import  ChangesetComment
 
    ChangesetComment().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `notifications`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import  Notification
 
    Notification().__table__.create()
 

	
 
    #==========================================================================
 
    # Add table `user_to_notification`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import  UserNotification
 
    UserNotification().__table__.create()
 

	
 
    #==========================================================================
 
    # Add unique to table `users_group_to_perm`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UsersGroupToPerm
 
    tbl = UsersGroupToPerm().__table__
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UserGroupToPerm
 
    tbl = UserGroupToPerm().__table__
 
    cons = UniqueConstraint('users_group_id', 'permission_id', table=tbl)
 
    cons.create()
 

	
 
    #==========================================================================
 
    # Fix unique constrain on table `user_logs`
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UserLog
 
    tbl = UserLog().__table__
 
    col = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'),
 
                 nullable=False, unique=None, default=None)
 
    col.alter(nullable=True, table=tbl)
 

	
rhodecode/lib/dbmigrate/versions/006_version_1_4_0.py
Show inline comments
 
@@ -65,26 +65,26 @@ def upgrade(migrate_engine):
 
    col.alter(name="firstname", table=tbl)
 

	
 
    # add inherit_default_permission column
 
    inherit_default_permissions = Column("inherit_default_permissions",
 
                                         Boolean(), nullable=True, unique=None,
 
                                         default=True)
 
    inherit_default_permissions.create(table=tbl)
 
    inherit_default_permissions.alter(nullable=False, default=True, table=tbl)
 

	
 
    #==========================================================================
 
    # USERS GROUP TABLE
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UsersGroup
 
    tbl = UsersGroup.__table__
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import UserGroup
 
    tbl = UserGroup.__table__
 
    # add inherit_default_permission column
 
    gr_inherit_default_permissions = Column(
 
                                    "users_group_inherit_default_permissions",
 
                                    Boolean(), nullable=True, unique=None,
 
                                    default=True)
 
    gr_inherit_default_permissions.create(table=tbl)
 
    gr_inherit_default_permissions.alter(nullable=False, default=True, table=tbl)
 

	
 
    #==========================================================================
 
    # REPOSITORIES
 
    #==========================================================================
 
    from rhodecode.lib.dbmigrate.schema.db_1_3_0 import Repository
rhodecode/lib/exceptions.py
Show inline comments
 
@@ -41,25 +41,25 @@ class LdapConnectionError(Exception):
 
class LdapImportError(Exception):
 
    pass
 

	
 

	
 
class DefaultUserException(Exception):
 
    pass
 

	
 

	
 
class UserOwnsReposException(Exception):
 
    pass
 

	
 

	
 
class UsersGroupsAssignedException(Exception):
 
class UserGroupsAssignedException(Exception):
 
    pass
 

	
 

	
 
class StatusChangeOnClosedPullRequestError(Exception):
 
    pass
 

	
 

	
 
class HTTPLockedRC(HTTPClientError):
 
    """
 
    Special Exception For locked Repos in RhodeCode
 
    """
 
    code = 423
rhodecode/lib/helpers.py
Show inline comments
 
@@ -675,27 +675,27 @@ def action_parser(user_log, feed=False, 
 
    'admin_deleted_repo':          (_('[delete] repository'),
 
                                    None, 'database_delete.png'),
 
    'admin_created_repo':          (_('[created] repository'),
 
                                    None, 'database_add.png'),
 
    'admin_forked_repo':           (_('[forked] repository'),
 
                                    None, 'arrow_divide.png'),
 
    'admin_updated_repo':          (_('[updated] repository'),
 
                                    None, 'database_edit.png'),
 
    'admin_created_user':          (_('[created] user'),
 
                                    get_user_name, 'user_add.png'),
 
    'admin_updated_user':          (_('[updated] user'),
 
                                    get_user_name, 'user_edit.png'),
 
    'admin_created_users_group':   (_('[created] users group'),
 
    'admin_created_users_group':   (_('[created] user group'),
 
                                    get_users_group, 'group_add.png'),
 
    'admin_updated_users_group':   (_('[updated] users group'),
 
    'admin_updated_users_group':   (_('[updated] user group'),
 
                                    get_users_group, 'group_edit.png'),
 
    'user_commented_revision':     (_('[commented] on revision in repository'),
 
                                    get_cs_links, 'comment_add.png'),
 
    'user_commented_pull_request': (_('[commented] on pull request for'),
 
                                    get_pull_request, 'comment_add.png'),
 
    'user_closed_pull_request':    (_('[closed] pull request for'),
 
                                    get_pull_request, 'tick.png'),
 
    'push':                        (_('[pushed] into'),
 
                                    get_cs_links, 'script_add.png'),
 
    'push_local':                  (_('[committed via RhodeCode] into repository'),
 
                                    get_cs_links, 'script_edit.png'),
 
    'push_remote':                 (_('[pulled from remote] into repository'),
 
@@ -968,64 +968,61 @@ def fancy_file_stats(stats):
 
    a_v = a if a > 0 else ''
 
    d_v = d if d > 0 else ''
 

	
 
    d_a = '<div class="added %s" style="width:%s%%">%s</div>' % (
 
        cgen('a', a_v, d_v), a_p, a_v
 
    )
 
    d_d = '<div class="deleted %s" style="width:%s%%">%s</div>' % (
 
        cgen('d', a_v, d_v), d_p, d_v
 
    )
 
    return literal('<div style="width:%spx">%s%s</div>' % (width, d_a, d_d))
 

	
 

	
 
def urlify_text(text_):
 
def urlify_text(text_, safe=True):
 
    """
 
    Extrac urls from text and make html links out of them
 

	
 
    :param text_:
 
    """
 

	
 
    url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]'''
 
                         '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''')
 

	
 
    def url_func(match_obj):
 
        url_full = match_obj.groups()[0]
 
        return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
 

	
 
    return literal(url_pat.sub(url_func, text_))
 
    _newtext = url_pat.sub(url_func, text_)
 
    if safe:
 
        return literal(_newtext)
 
    return _newtext
 

	
 

	
 
def urlify_changesets(text_, repository):
 
    """
 
    Extract revision ids from changeset and make link from them
 

	
 
    :param text_:
 
    :param repository: repo name to build the URL with
 
    """
 
    from pylons import url  # doh, we need to re-import url to mock it later
 
    URL_PAT = re.compile(r'(?:^|\s)([0-9a-fA-F]{12,40})(?:$|\s)')
 
    URL_PAT = re.compile(r'(^|\s)([0-9a-fA-F]{12,40})($|\s)')
 

	
 
    def url_func(match_obj):
 
        rev = match_obj.groups()[0]
 
        pref = ''
 
        suf = ''
 
        if match_obj.group().startswith(' '):
 
            pref = ' '
 
        if match_obj.group().endswith(' '):
 
            suf = ' '
 
        rev = match_obj.groups()[1]
 
        pref = match_obj.groups()[0]
 
        suf = match_obj.groups()[2]
 

	
 
        tmpl = (
 
        '%(pref)s<a class="%(cls)s" href="%(url)s">'
 
        '%(rev)s'
 
        '</a>'
 
        '%(suf)s'
 
        '%(rev)s</a>%(suf)s'
 
        )
 
        return tmpl % {
 
         'pref': pref,
 
         'cls': 'revision-link',
 
         'url': url('changeset_home', repo_name=repository, revision=rev),
 
         'rev': rev,
 
         'suf': suf
 
        }
 

	
 
    newtext = URL_PAT.sub(url_func, text_)
 

	
 
    return newtext
 
@@ -1053,25 +1050,25 @@ def urlify_commit(text_, repository=None
 
        for e in urls.split(t):
 
            if not urls.match(e):
 
                links.append('<a class="message-link" href="%s">%s</a>' % (l, e))
 
            else:
 
                links.append(e)
 

	
 
        return ''.join(links)
 

	
 
    # urlify changesets - extrac revisions and make link out of them
 
    newtext = urlify_changesets(escaper(text_), repository)
 

	
 
    # extract http/https links and make them real urls
 
    newtext = urlify_text(newtext)
 
    newtext = urlify_text(newtext, safe=False)
 

	
 
    try:
 
        from rhodecode import CONFIG
 
        conf = CONFIG
 

	
 
        # allow multiple issue servers to be used
 
        valid_indices = [
 
            x.group(1)
 
            for x in map(lambda x: re.match(r'issue_pat(.*)', x), conf.keys())
 
            if x and 'issue_server_link%s' % x.group(1) in conf
 
            and 'issue_prefix%s' % x.group(1) in conf
 
        ]
rhodecode/lib/unionrepo.py
Show inline comments
 
# unionrepo.py - repository class for viewing union of repositories
 
# unionrepo.py - repository class for viewing union of repository changesets
 
#
 
# Derived from Mercurial 2.5 bundlerepo.py
 
# Derived from bundlerepo.py
 
# Copyright 2006, 2007 Benoit Boissinot <bboissin@gmail.com>
 
# Copyright 2013 Unity Technologies, Mads Kiilerich <madski@unity3d.com>
 
#
 
# This software may be used and distributed according to the terms of the
 
# GNU General Public License version 2 or any later version.
 

	
 
"""Repository class for in-memory pull of one local repository to another.
 
"""Repository class for "in-memory pull" of one local repository to another,
 
allowing operations like diff and log with revsets.
 
"""
 

	
 
import os
 
from mercurial.node import nullid
 
from mercurial import util, mdiff
 
from mercurial.i18n import _
 
from mercurial import util, mdiff, cmdutil, scmutil
 
from mercurial import localrepo, changelog, manifest, filelog, revlog
 

	
 
class unionrevlog(revlog.revlog):
 
    def __init__(self, opener, indexfile, revlog2, linkmapper):
 
        # How it works:
 
        # To retrieve a revision, we just need to know the node id so we can
 
        # look it up in revlog2.
 
        #
 
        # basemap is indexed with revisions coming from the second revlog.
 
        #
 
        # To differentiate a rev in the second revlog from a rev in the revlog,
 
        # we check revision against basemap.
 
        # we check revision against repotiprev.
 
        opener = scmutil.readonlyvfs(opener)
 
        revlog.revlog.__init__(self, opener, indexfile)
 
        self.revlog2 = revlog2
 

	
 
        self.basemap = {} # mapping rev that is in revlog2 to ... nothing
 
        n = len(self)
 
        self.repotiprev = n - 1
 
        self.bundlerevs = set() # used by 'bundle()' revset expression
 
        for rev2 in self.revlog2:
 
            rev = self.revlog2.index[rev2]
 
            # rev numbers - in revlog2, very different from self.rev
 
            _start, _csize, _rsize, _base, linkrev, p1rev, p2rev, node = rev
 

	
 
            if linkmapper is None: # link is to same revlog
 
                assert linkrev == rev2 # we never link back
 
                link = n
 
            else: # rev must be mapped from repo2 cl to unified cl by linkmapper
 
                link = linkmapper(linkrev)
 

	
 
            if node in self.nodemap:
 
                # this happens for for the common revlog revisions
 
                # this happens for the common revlog revisions
 
                self.bundlerevs.add(self.nodemap[node])
 
                continue
 

	
 
            p1node = self.revlog2.node(p1rev)
 
            p2node = self.revlog2.node(p2rev)
 

	
 
            e = (None, None, None, None,
 
                 link, self.rev(p1node), self.rev(p2node), node)
 
            self.basemap[n] = None
 
            self.index.insert(-1, e)
 
            self.nodemap[node] = n
 
            self.bundlerevs.add(n)
 
            n += 1
 

	
 
    def _chunk(self, rev):
 
        if rev not in self.basemap:
 
        if rev <= self.repotiprev:
 
            return revlog.revlog._chunk(self, rev)
 
        return self.revlog2._chunk(self.node(rev))
 

	
 
    def revdiff(self, rev1, rev2):
 
        """return or calculate a delta between two revisions"""
 
        if rev1 in self.basemap and rev2 in self.basemap:
 
        if rev1 > self.repotiprev and rev2 > self.repotiprev:
 
            return self.revlog2.revdiff(
 
                self.revlog2.rev(self.node(rev1)),
 
                self.revlog2.rev(self.node(rev2)))
 
        elif rev1 not in self.basemap and rev2 not in self.basemap:
 
        elif rev1 <= self.repotiprev and rev2 <= self.repotiprev:
 
            return revlog.revlog.revdiff(self, rev1, rev2)
 

	
 
        return mdiff.textdiff(self.revision(self.node(rev1)),
 
                              self.revision(self.node(rev2)))
 

	
 
    def revision(self, nodeorrev):
 
        """return an uncompressed revision of a given node or revision
 
        number.
 
        """
 
        if isinstance(nodeorrev, int):
 
            rev = nodeorrev
 
            node = self.node(rev)
 
        else:
 
            node = nodeorrev
 
            rev = self.rev(node)
 

	
 
        if node == nullid:
 
            return ""
 

	
 
        if rev in self.basemap:
 
        if rev > self.repotiprev:
 
            text = self.revlog2.revision(node)
 
            self._cache = (node, rev, text)
 
        else:
 
            text = revlog.revlog.revision(self, rev)
 
            # already cached
 
        return text
 

	
 
    def addrevision(self, text, transaction, link, p1=None, p2=None, d=None):
 
        raise NotImplementedError
 
    def addgroup(self, revs, linkmapper, transaction):
 
        raise NotImplementedError
 
    def strip(self, rev, minlink):
 
@@ -135,47 +136,73 @@ class unionpeer(localrepo.localpeer):
 
    def canpush(self):
 
        return False
 

	
 
class unionrepository(localrepo.localrepository):
 
    def __init__(self, ui, path, path2):
 
        localrepo.localrepository.__init__(self, ui, path)
 
        self.ui.setconfig('phases', 'publish', False)
 

	
 
        self._url = 'union:%s+%s' % (util.expandpath(path),
 
                                     util.expandpath(path2))
 
        self.repo2 = localrepo.localrepository(ui, path2)
 

	
 
    @util.propertycache
 
    @localrepo.unfilteredpropertycache
 
    def changelog(self):
 
        return unionchangelog(self.sopener, self.repo2.sopener)
 

	
 
    def _clrev(self, rev2):
 
        """map from repo2 changelog rev to temporary rev in self.changelog"""
 
        node = self.repo2.changelog.node(rev2)
 
        return self.changelog.rev(node)
 

	
 
    @util.propertycache
 
    @localrepo.unfilteredpropertycache
 
    def manifest(self):
 
        return unionmanifest(self.sopener, self.repo2.sopener,
 
                             self._clrev)
 

	
 
    def url(self):
 
        return self._url
 

	
 
    def file(self, f):
 
        return unionfilelog(self.sopener, f, self.repo2.sopener,
 
                            self._clrev, self)
 

	
 
    def close(self):
 
        self.repo2.close()
 

	
 
    def cancopy(self):
 
        return False
 

	
 
    def peer(self):
 
        return unionpeer(self)
 

	
 
    def getcwd(self):
 
        return os.getcwd() # always outside the repo
 

	
 
def instance(ui, path, create):
 
    u = util.url(path)
 
    assert u.scheme == 'union'
 
    repopath, repopath2 = u.path.split("+", 1)
 
    if create:
 
        raise util.Abort(_('cannot create new union repository'))
 
    parentpath = ui.config("bundle", "mainreporoot", "")
 
    if not parentpath:
 
        # try to find the correct path to the working directory repo
 
        parentpath = cmdutil.findrepo(os.getcwd())
 
        if parentpath is None:
 
            parentpath = ''
 
    if parentpath:
 
        # Try to make the full path relative so we get a nice, short URL.
 
        # In particular, we don't want temp dir names in test outputs.
 
        cwd = os.getcwd()
 
        if parentpath == cwd:
 
            parentpath = ''
 
        else:
 
            cwd = os.path.join(cwd,'')
 
            if parentpath.startswith(cwd):
 
                parentpath = parentpath[len(cwd):]
 
    if path.startswith('union:'):
 
        s = path.split(":", 1)[1].split("+", 1)
 
        if len(s) == 1:
 
            repopath, repopath2 = parentpath, s[0]
 
        else:
 
            repopath, repopath2 = s
 
    else:
 
        repopath, repopath2 = parentpath, path
 
    return unionrepository(ui, repopath, repopath2)
rhodecode/lib/vcs/utils/lockfiles.py
Show inline comments
 
import os
 

	
 

	
 
class LockFile(object):
 
	"""Provides methods to obtain, check for, and release a file based lock which
 
	should be used to handle concurrent access to the same file.
 
    """Provides methods to obtain, check for, and release a file based lock which
 
    should be used to handle concurrent access to the same file.
 

	
 
	As we are a utility class to be derived from, we only use protected methods.
 
    As we are a utility class to be derived from, we only use protected methods.
 

	
 
	Locks will automatically be released on destruction"""
 
	__slots__ = ("_file_path", "_owns_lock")
 
    Locks will automatically be released on destruction"""
 
    __slots__ = ("_file_path", "_owns_lock")
 

	
 
	def __init__(self, file_path):
 
		self._file_path = file_path
 
		self._owns_lock = False
 
    def __init__(self, file_path):
 
        self._file_path = file_path
 
        self._owns_lock = False
 

	
 
	def __del__(self):
 
		self._release_lock()
 
    def __del__(self):
 
        self._release_lock()
 

	
 
	def _lock_file_path(self):
 
		""":return: Path to lockfile"""
 
		return "%s.lock" % (self._file_path)
 
    def _lock_file_path(self):
 
        """:return: Path to lockfile"""
 
        return "%s.lock" % (self._file_path)
 

	
 
	def _has_lock(self):
 
		""":return: True if we have a lock and if the lockfile still exists
 
		:raise AssertionError: if our lock-file does not exist"""
 
		if not self._owns_lock:
 
			return False
 
    def _has_lock(self):
 
        """:return: True if we have a lock and if the lockfile still exists
 
        :raise AssertionError: if our lock-file does not exist"""
 
        if not self._owns_lock:
 
            return False
 

	
 
		return True
 
        return True
 

	
 
	def _obtain_lock_or_raise(self):
 
		"""Create a lock file as flag for other instances, mark our instance as lock-holder
 
    def _obtain_lock_or_raise(self):
 
        """Create a lock file as flag for other instances, mark our instance as lock-holder
 

	
 
		:raise IOError: if a lock was already present or a lock file could not be written"""
 
		if self._has_lock():
 
			return
 
		lock_file = self._lock_file_path()
 
		if os.path.isfile(lock_file):
 
			raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file))
 
        :raise IOError: if a lock was already present or a lock file could not be written"""
 
        if self._has_lock():
 
            return
 
        lock_file = self._lock_file_path()
 
        if os.path.isfile(lock_file):
 
            raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file))
 

	
 
		try:
 
			fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0)
 
			os.close(fd)
 
		except OSError,e:
 
			raise IOError(str(e))
 
        try:
 
            fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0)
 
            os.close(fd)
 
        except OSError,e:
 
            raise IOError(str(e))
 

	
 
		self._owns_lock = True
 
        self._owns_lock = True
 

	
 
	def _obtain_lock(self):
 
		"""The default implementation will raise if a lock cannot be obtained.
 
		Subclasses may override this method to provide a different implementation"""
 
		return self._obtain_lock_or_raise()
 
    def _obtain_lock(self):
 
        """The default implementation will raise if a lock cannot be obtained.
 
        Subclasses may override this method to provide a different implementation"""
 
        return self._obtain_lock_or_raise()
 

	
 
	def _release_lock(self):
 
		"""Release our lock if we have one"""
 
		if not self._has_lock():
 
			return
 
    def _release_lock(self):
 
        """Release our lock if we have one"""
 
        if not self._has_lock():
 
            return
 

	
 
		# if someone removed our file beforhand, lets just flag this issue
 
		# instead of failing, to make it more usable.
 
		lfp = self._lock_file_path()
 
		try:
 
			# on bloody windows, the file needs write permissions to be removable.
 
			# Why ...
 
			if os.name == 'nt':
 
				os.chmod(lfp, 0777)
 
			# END handle win32
 
			os.remove(lfp)
 
		except OSError:
 
			pass
 
		self._owns_lock = False
 
        # if someone removed our file beforhand, lets just flag this issue
 
        # instead of failing, to make it more usable.
 
        lfp = self._lock_file_path()
 
        try:
 
            # on bloody windows, the file needs write permissions to be removable.
 
            # Why ...
 
            if os.name == 'nt':
 
                os.chmod(lfp, 0777)
 
            # END handle win32
 
            os.remove(lfp)
 
        except OSError:
 
            pass
 
        self._owns_lock = False
rhodecode/model/comment.py
Show inline comments
 
@@ -26,216 +26,251 @@
 
import logging
 
import traceback
 

	
 
from pylons.i18n.translation import _
 
from sqlalchemy.util.compat import defaultdict
 

	
 
from rhodecode.lib.utils2 import extract_mentioned_users, safe_unicode
 
from rhodecode.lib import helpers as h
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import ChangesetComment, User, Repository, \
 
    Notification, PullRequest
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetCommentsModel(BaseModel):
 

	
 
    cls = ChangesetComment
 

	
 
    def __get_changeset_comment(self, changeset_comment):
 
        return self._get_instance(ChangesetComment, changeset_comment)
 

	
 
    def __get_pull_request(self, pull_request):
 
        return self._get_instance(PullRequest, pull_request)
 

	
 
    def _extract_mentions(self, s):
 
        user_objects = []
 
        for username in extract_mentioned_users(s):
 
            user_obj = User.get_by_username(username, case_insensitive=True)
 
            if user_obj:
 
                user_objects.append(user_obj)
 
        return user_objects
 

	
 
    def _get_notification_data(self, repo, comment, user, comment_text,
 
                               line_no=None, revision=None, pull_request=None,
 
                               status_change=None, closing_pr=False):
 
        """
 
        Get notification data
 

	
 
        :param comment_text:
 
        :param line:
 
        :returns: tuple (subj,body,recipients,notification_type,email_kwargs)
 
        """
 
        # make notification
 
        body = comment_text  # text of the comment
 
        line = ''
 
        if line_no:
 
            line = _('on line %s') % line_no
 

	
 
        #changeset
 
        if revision:
 
            notification_type = Notification.TYPE_CHANGESET_COMMENT
 
            cs = repo.scm_instance.get_changeset(revision)
 
            desc = "%s" % (cs.short_id)
 

	
 
            _url = h.url('changeset_home',
 
                repo_name=repo.repo_name,
 
                revision=revision,
 
                anchor='comment-%s' % comment.comment_id,
 
                qualified=True,
 
            )
 
            subj = safe_unicode(
 
                h.link_to('Re changeset: %(desc)s %(line)s' % \
 
                          {'desc': desc, 'line': line},
 
                          _url)
 
            )
 
            email_subject = 'User %s commented on changeset %s' % \
 
                (user.username, h.short_id(revision))
 
            # get the current participants of this changeset
 
            recipients = ChangesetComment.get_users(revision=revision)
 
            # add changeset author if it's in rhodecode system
 
            cs_author = User.get_from_cs_author(cs.author)
 
            if not cs_author:
 
                #use repo owner if we cannot extract the author correctly
 
                cs_author = repo.user
 
            recipients += [cs_author]
 
            email_kwargs = {
 
                'status_change': status_change,
 
                'cs_comment_user': h.person(user.email),
 
                'cs_target_repo': h.url('summary_home', repo_name=repo.repo_name,
 
                                        qualified=True),
 
                'cs_comment_url': _url,
 
                'raw_id': revision,
 
                'message': cs.message
 
            }
 
        #pull request
 
        elif pull_request:
 
            notification_type = Notification.TYPE_PULL_REQUEST_COMMENT
 
            desc = comment.pull_request.title
 
            _url = h.url('pullrequest_show',
 
                repo_name=pull_request.other_repo.repo_name,
 
                pull_request_id=pull_request.pull_request_id,
 
                anchor='comment-%s' % comment.comment_id,
 
                qualified=True,
 
            )
 
            subj = safe_unicode(
 
                h.link_to('Re pull request #%(pr_id)s: %(desc)s %(line)s' % \
 
                          {'desc': desc,
 
                           'pr_id': comment.pull_request.pull_request_id,
 
                           'line': line},
 
                          _url)
 
            )
 
            email_subject = 'User %s commented on pull request #%s' % \
 
                    (user.username, comment.pull_request.pull_request_id)
 
            # get the current participants of this pull request
 
            recipients = ChangesetComment.get_users(pull_request_id=
 
                                                pull_request.pull_request_id)
 
            # add pull request author
 
            recipients += [pull_request.author]
 

	
 
            # add the reviewers to notification
 
            recipients += [x.user for x in pull_request.reviewers]
 

	
 
            #set some variables for email notification
 
            email_kwargs = {
 
                'pr_id': pull_request.pull_request_id,
 
                'status_change': status_change,
 
                'closing_pr': closing_pr,
 
                'pr_comment_url': _url,
 
                'pr_comment_user': h.person(user.email),
 
                'pr_target_repo': h.url('summary_home',
 
                                   repo_name=pull_request.other_repo.repo_name,
 
                                   qualified=True)
 
            }
 

	
 
        return subj, body, recipients, notification_type, email_kwargs, email_subject
 

	
 
    def create(self, text, repo, user, revision=None, pull_request=None,
 
               f_path=None, line_no=None, status_change=None, send_email=True):
 
               f_path=None, line_no=None, status_change=None, closing_pr=False,
 
               send_email=True):
 
        """
 
        Creates new comment for changeset or pull request.
 
        IF status_change is not none this comment is associated with a
 
        status change of changeset or changesets associated with pull request
 

	
 
        :param text:
 
        :param repo:
 
        :param user:
 
        :param revision:
 
        :param pull_request:
 
        :param f_path:
 
        :param line_no:
 
        :param status_change:
 
        :param closing_pr:
 
        :param send_email:
 
        """
 
        if not text:
 
            log.warning('Missing text for comment, skipping...')
 
            return
 

	
 
        repo = self._get_repo(repo)
 
        user = self._get_user(user)
 
        comment = ChangesetComment()
 
        comment.repo = repo
 
        comment.author = user
 
        comment.text = text
 
        comment.f_path = f_path
 
        comment.line_no = line_no
 

	
 
        if revision:
 
            cs = repo.scm_instance.get_changeset(revision)
 
            desc = "%s - %s" % (cs.short_id, h.shorter(cs.message, 256))
 
            comment.revision = revision
 
        elif pull_request:
 
            pull_request = self.__get_pull_request(pull_request)
 
            comment.pull_request = pull_request
 
        else:
 
            raise Exception('Please specify revision or pull_request_id')
 

	
 
        self.sa.add(comment)
 
        self.sa.flush()
 

	
 
        # make notification
 
        line = ''
 
        body = text
 

	
 
        #changeset
 
        if revision:
 
            if line_no:
 
                line = _('on line %s') % line_no
 
            subj = safe_unicode(
 
                h.link_to('Re commit: %(desc)s %(line)s' % \
 
                          {'desc': desc, 'line': line},
 
                          h.url('changeset_home', repo_name=repo.repo_name,
 
                                revision=revision,
 
                                anchor='comment-%s' % comment.comment_id,
 
                                qualified=True,
 
                          )
 
                )
 
            )
 
            notification_type = Notification.TYPE_CHANGESET_COMMENT
 
            # get the current participants of this changeset
 
            recipients = ChangesetComment.get_users(revision=revision)
 
            # add changeset author if it's in rhodecode system
 
            cs_author = User.get_from_cs_author(cs.author)
 
            if not cs_author:
 
                #use repo owner if we cannot extract the author correctly
 
                cs_author = repo.user
 
            recipients += [cs_author]
 
            email_kwargs = {
 
                'status_change': status_change,
 
            }
 
        #pull request
 
        elif pull_request:
 
            _url = h.url('pullrequest_show',
 
                repo_name=pull_request.other_repo.repo_name,
 
                pull_request_id=pull_request.pull_request_id,
 
                anchor='comment-%s' % comment.comment_id,
 
                qualified=True,
 
            )
 
            subj = safe_unicode(
 
                h.link_to('Re pull request #%(pr_id)s: %(desc)s %(line)s' % \
 
                          {'desc': comment.pull_request.title,
 
                           'pr_id': comment.pull_request.pull_request_id,
 
                           'line': line},
 
                          _url)
 
            )
 

	
 
            notification_type = Notification.TYPE_PULL_REQUEST_COMMENT
 
            # get the current participants of this pull request
 
            recipients = ChangesetComment.get_users(pull_request_id=
 
                                                pull_request.pull_request_id)
 
            # add pull request author
 
            recipients += [pull_request.author]
 

	
 
            # add the reviewers to notification
 
            recipients += [x.user for x in pull_request.reviewers]
 

	
 
            #set some variables for email notification
 
            email_kwargs = {
 
                'pr_id': pull_request.pull_request_id,
 
                'status_change': status_change,
 
                'pr_comment_url': _url,
 
                'pr_comment_user': h.person(user.email),
 
                'pr_target_repo': h.url('summary_home',
 
                                   repo_name=pull_request.other_repo.repo_name,
 
                                   qualified=True)
 
            }
 
        Session().add(comment)
 
        Session().flush()
 

	
 
        if send_email:
 
            (subj, body, recipients, notification_type,
 
             email_kwargs, email_subject) = self._get_notification_data(
 
                                repo, comment, user,
 
                                comment_text=text,
 
                                line_no=line_no,
 
                                revision=revision,
 
                                pull_request=pull_request,
 
                                status_change=status_change,
 
                                closing_pr=closing_pr)
 
            # create notification objects, and emails
 
            NotificationModel().create(
 
                created_by=user, subject=subj, body=body,
 
                recipients=recipients, type_=notification_type,
 
                email_kwargs=email_kwargs
 
                email_kwargs=email_kwargs, email_subject=email_subject
 
            )
 

	
 
            mention_recipients = set(self._extract_mentions(body))\
 
                                    .difference(recipients)
 
            if mention_recipients:
 
                email_kwargs.update({'pr_mention': True})
 
                subj = _('[Mention]') + ' ' + subj
 
                NotificationModel().create(
 
                    created_by=user, subject=subj, body=body,
 
                    recipients=mention_recipients,
 
                    type_=notification_type,
 
                    email_kwargs=email_kwargs
 
                )
 

	
 
        return comment
 

	
 
    def delete(self, comment):
 
        """
 
        Deletes given comment
 

	
 
        :param comment_id:
 
        """
 
        comment = self.__get_changeset_comment(comment)
 
        self.sa.delete(comment)
 
        Session().delete(comment)
 

	
 
        return comment
 

	
 
    def get_comments(self, repo_id, revision=None, pull_request=None):
 
        """
 
        Get's main comments based on revision or pull_request_id
 

	
 
        :param repo_id:
 
        :type repo_id:
 
        :param revision:
 
        :type revision:
 
        :param pull_request:
 
        :type pull_request:
 
        """
 

	
 
        q = ChangesetComment.query()\
 
                .filter(ChangesetComment.repo_id == repo_id)\
 
                .filter(ChangesetComment.line_no == None)\
 
                .filter(ChangesetComment.f_path == None)
 
        if revision:
 
            q = q.filter(ChangesetComment.revision == revision)
 
        elif pull_request:
 
            pull_request = self.__get_pull_request(pull_request)
 
            q = q.filter(ChangesetComment.pull_request == pull_request)
 
        else:
 
            raise Exception('Please specify revision or pull_request')
 
        q = q.order_by(ChangesetComment.created_on)
 
        return q.all()
 

	
 
    def get_inline_comments(self, repo_id, revision=None, pull_request=None):
 
        q = self.sa.query(ChangesetComment)\
 
        q = Session().query(ChangesetComment)\
 
            .filter(ChangesetComment.repo_id == repo_id)\
 
            .filter(ChangesetComment.line_no != None)\
 
            .filter(ChangesetComment.f_path != None)\
 
            .order_by(ChangesetComment.comment_id.asc())\
 

	
 
        if revision:
 
            q = q.filter(ChangesetComment.revision == revision)
 
        elif pull_request:
 
            pull_request = self.__get_pull_request(pull_request)
 
            q = q.filter(ChangesetComment.pull_request == pull_request)
 
        else:
 
            raise Exception('Please specify revision or pull_request_id')
rhodecode/model/db.py
Show inline comments
 
@@ -35,24 +35,25 @@ from sqlalchemy import *
 
from sqlalchemy.ext.hybrid import hybrid_property
 
from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
 
from sqlalchemy.exc import DatabaseError
 
from beaker.cache import cache_region, region_invalidate
 
from webob.exc import HTTPNotFound
 

	
 
from pylons.i18n.translation import lazy_ugettext as _
 

	
 
from rhodecode.lib.vcs import get_backend
 
from rhodecode.lib.vcs.utils.helpers import get_scm
 
from rhodecode.lib.vcs.exceptions import VCSError
 
from rhodecode.lib.vcs.utils.lazy import LazyProperty
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 

	
 
from rhodecode.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
 
    safe_unicode, remove_suffix, remove_prefix
 
from rhodecode.lib.compat import json
 
from rhodecode.lib.caching_query import FromCache
 

	
 
from rhodecode.model.meta import Base, Session
 

	
 
URL_SEP = '/'
 
log = logging.getLogger(__name__)
 

	
 
#==============================================================================
 
@@ -332,25 +333,25 @@ class User(Base, BaseModel):
 
    inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    user_log = relationship('UserLog')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
 

	
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 
    group_member = relationship('UserGroupMember', cascade='all')
 

	
 
    notifications = relationship('UserNotification', cascade='all')
 
    # notifications assigned to this user
 
    user_created_notifications = relationship('Notification', cascade='all')
 
    # comments created by this user
 
    user_comments = relationship('ChangesetComment', cascade='all')
 
    #extra emails for this user
 
    user_emails = relationship('UserEmailMap', cascade='all')
 

	
 
    @hybrid_property
 
    def email(self):
 
        return self._email
 
@@ -595,39 +596,39 @@ class UserLog(Base, BaseModel):
 
    user_ip = Column("user_ip", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
 

	
 
    @property
 
    def action_as_day(self):
 
        return datetime.date(*self.action_date.timetuple()[:3])
 

	
 
    user = relationship('User')
 
    repository = relationship('Repository', cascade='')
 

	
 

	
 
class UsersGroup(Base, BaseModel):
 
class UserGroup(Base, BaseModel):
 
    __tablename__ = 'users_groups'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_name = Column("users_group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
 
    inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
 

	
 
    members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UsersGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
 
    users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
 
    users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 

	
 
    def __unicode__(self):
 
        return u'<userGroup(%s)>' % (self.users_group_name)
 

	
 
    @classmethod
 
    def get_by_group_name(cls, group_name, cache=False,
 
                          case_insensitive=False):
 
        if case_insensitive:
 
            q = cls.query().filter(cls.users_group_name.ilike(group_name))
 
        else:
 
            q = cls.query().filter(cls.users_group_name == group_name)
 
        if cache:
 
@@ -649,37 +650,37 @@ class UsersGroup(Base, BaseModel):
 
    def get_api_data(self):
 
        users_group = self
 

	
 
        data = dict(
 
            users_group_id=users_group.users_group_id,
 
            group_name=users_group.users_group_name,
 
            active=users_group.users_group_active,
 
        )
 

	
 
        return data
 

	
 

	
 
class UsersGroupMember(Base, BaseModel):
 
class UserGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = (
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 

	
 
class RepositoryField(Base, BaseModel):
 
    __tablename__ = 'repositories_fields'
 
    __table_args__ = (
 
        UniqueConstraint('repository_id', 'field_key'),  # no-multi field
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
@@ -738,25 +739,25 @@ class Repository(Base, BaseModel):
 
    landing_rev = Column("landing_revision", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 
    _locked = Column("locked", String(255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
 
    _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) #JSON data
 

	
 
    fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
 

	
 
    user = relationship('User')
 
    fork = relationship('Repository', remote_side=repo_id)
 
    group = relationship('RepoGroup')
 
    repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
 
    stats = relationship('Statistics', cascade='all', uselist=False)
 

	
 
    followers = relationship('UserFollowing',
 
                             primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
 
                             cascade='all')
 
    extra_fields = relationship('RepositoryField',
 
                                cascade="all, delete, delete-orphan")
 

	
 
    logs = relationship('UserLog')
 
    comments = relationship('ChangesetComment', cascade="all, delete, delete-orphan")
 

	
 
    pull_requests_org = relationship('PullRequest',
 
@@ -1044,33 +1045,36 @@ class Repository(Base, BaseModel):
 

	
 
            short_id
 
            raw_id
 
            revision
 
            message
 
            date
 
            author
 

	
 
        :param cs_cache:
 
        """
 
        from rhodecode.lib.vcs.backends.base import BaseChangeset
 
        if cs_cache is None:
 
            cs_cache = self.get_changeset()
 
            cs_cache = EmptyChangeset()
 
            # use no-cache version here
 
            scm_repo = self.scm_instance_no_cache
 
            if scm_repo:
 
                cs_cache = scm_repo.get_changeset()
 

	
 
        if isinstance(cs_cache, BaseChangeset):
 
            cs_cache = cs_cache.__json__()
 

	
 
        if (cs_cache != self.changeset_cache
 
            or not self.last_change
 
            or not self.changeset_cache):
 
        if (cs_cache != self.changeset_cache or not self.changeset_cache):
 
            _default = datetime.datetime.fromtimestamp(0)
 
            last_change = cs_cache.get('date') or self.last_change or _default
 
            last_change = cs_cache.get('date') or _default
 
            log.debug('updated repo %s with new cs cache %s' % (self, cs_cache))
 
            self.updated_on = last_change
 
            self.changeset_cache = cs_cache
 
            Session().add(self)
 
            Session().commit()
 
        else:
 
            log.debug('Skipping repo:%s already with latest changes' % self)
 

	
 
    @property
 
    def tip(self):
 
        return self.get_changeset('tip')
 

	
 
@@ -1179,25 +1183,26 @@ class Repository(Base, BaseModel):
 
            invalidate_repo = self.invalidate
 

	
 
        if invalidate_repo is not None:
 
            region_invalidate(_c, None, rn)
 
            # update our cache
 
            CacheInvalidation.set_valid(invalidate_repo.cache_key)
 
        return _c(rn)
 

	
 
    def __get_instance(self):
 
        repo_full_path = self.repo_full_path
 
        try:
 
            alias = get_scm(repo_full_path)[0]
 
            log.debug('Creating instance of %s repository' % alias)
 
            log.debug('Creating instance of %s repository from %s'
 
                      % (alias, repo_full_path))
 
            backend = get_backend(alias)
 
        except VCSError:
 
            log.error(traceback.format_exc())
 
            log.error('Perhaps this repository is in db and not in '
 
                      'filesystem run rescan repositories with '
 
                      '"destroy old data " option from admin panel')
 
            return
 

	
 
        if alias == 'hg':
 

	
 
            repo = backend(safe_str(repo_full_path), create=False,
 
                           baseui=self._ui)
 
@@ -1218,25 +1223,25 @@ class RepoGroup(Base, BaseModel):
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 
    __mapper_args__ = {'order_by': 'group_name'}
 

	
 
    group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    group_name = Column("group_name", String(255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
 
    group_description = Column("group_description", String(10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
 

	
 
    repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
 
    users_group_to_perm = relationship('UsersGroupRepoGroupToPerm', cascade='all')
 
    users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
 

	
 
    parent_group = relationship('RepoGroup', remote_side=group_id)
 

	
 
    def __init__(self, group_name='', parent_group=None):
 
        self.group_name = group_name
 
        self.parent_group = parent_group
 

	
 
    def __unicode__(self):
 
        return u"<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
 
                                  self.group_name)
 

	
 
    @classmethod
 
@@ -1369,28 +1374,28 @@ class Permission(Base, BaseModel):
 
    __tablename__ = 'permissions'
 
    __table_args__ = (
 
        Index('p_perm_name_idx', 'permission_name'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'},
 
    )
 
    PERMS = [
 
        ('repository.none', _('Repository no access')),
 
        ('repository.read', _('Repository read access')),
 
        ('repository.write', _('Repository write access')),
 
        ('repository.admin', _('Repository admin access')),
 

	
 
        ('group.none', _('Repositories Group no access')),
 
        ('group.read', _('Repositories Group read access')),
 
        ('group.write', _('Repositories Group write access')),
 
        ('group.admin', _('Repositories Group admin access')),
 
        ('group.none', _('Repository group no access')),
 
        ('group.read', _('Repository group read access')),
 
        ('group.write', _('Repository group write access')),
 
        ('group.admin', _('Repository group admin access')),
 

	
 
        ('hg.admin', _('RhodeCode Administrator')),
 
        ('hg.create.none', _('Repository creation disabled')),
 
        ('hg.create.repository', _('Repository creation enabled')),
 
        ('hg.fork.none', _('Repository forking disabled')),
 
        ('hg.fork.repository', _('Repository forking enabled')),
 
        ('hg.register.none', _('Register disabled')),
 
        ('hg.register.manual_activate', _('Register new user with RhodeCode '
 
                                          'with manual activation')),
 

	
 
        ('hg.register.auto_activate', _('Register new user with RhodeCode '
 
                                        'with auto activation')),
 
@@ -1481,100 +1486,100 @@ class UserToPerm(Base, BaseModel):
 
        UniqueConstraint('user_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    permission = relationship('Permission', lazy='joined')
 

	
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
class UserGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 

	
 
    @classmethod
 
    def create(cls, users_group, repository, permission):
 
        n = cls()
 
        n.users_group = users_group
 
        n.repository = repository
 
        n.permission = permission
 
        Session().add(n)
 
        return n
 

	
 
    def __unicode__(self):
 
        return u'<userGroup:%s => %s >' % (self.users_group, self.repository)
 

	
 

	
 
class UsersGroupToPerm(Base, BaseModel):
 
class UserGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'permission_id',),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'user_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('user_id', 'group_id', 'permission_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
    group = relationship('RepoGroup')
 
    permission = relationship('Permission')
 

	
 

	
 
class UsersGroupRepoGroupToPerm(Base, BaseModel):
 
class UserGroupRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_group_to_perm'
 
    __table_args__ = (
 
        UniqueConstraint('users_group_id', 'group_id'),
 
        {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
         'mysql_charset': 'utf8'}
 
    )
 

	
 
    users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    users_group = relationship('UserGroup')
 
    permission = relationship('Permission')
 
    group = relationship('RepoGroup')
 

	
 

	
 
class Statistics(Base, BaseModel):
 
    __tablename__ = 'statistics'
 
    __table_args__ = (
 
         UniqueConstraint('repository_id'),
 
         {'extend_existing': True, 'mysql_engine': 'InnoDB',
 
          'mysql_charset': 'utf8'}
 
    )
 
    stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
rhodecode/model/forms.py
Show inline comments
 
@@ -85,43 +85,43 @@ def UserForm(edit=False, old_data={}):
 
            )
 

	
 
        active = v.StringBoolean(if_missing=False)
 
        firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
 
        lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
 
        email = All(v.Email(not_empty=True), v.UniqSystemEmail(old_data))
 

	
 
        chained_validators = [v.ValidPasswordsMatch()]
 

	
 
    return _UserForm
 

	
 

	
 
def UsersGroupForm(edit=False, old_data={}, available_members=[]):
 
    class _UsersGroupForm(formencode.Schema):
 
def UserGroupForm(edit=False, old_data={}, available_members=[]):
 
    class _UserGroupForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = True
 

	
 
        users_group_name = All(
 
            v.UnicodeString(strip=True, min=1, not_empty=True),
 
            v.ValidUsersGroup(edit, old_data)
 
            v.ValidUserGroup(edit, old_data)
 
        )
 

	
 
        users_group_active = v.StringBoolean(if_missing=False)
 

	
 
        if edit:
 
            users_group_members = v.OneOf(
 
                available_members, hideList=False, testValueList=True,
 
                if_missing=None, not_empty=False
 
            )
 

	
 
    return _UsersGroupForm
 
    return _UserGroupForm
 

	
 

	
 
def ReposGroupForm(edit=False, old_data={}, available_groups=[],
 
                   can_create_in_root=False):
 
    class _ReposGroupForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 

	
 
        group_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
 
                               v.SlugifyName())
 
        group_description = v.UnicodeString(strip=True, min=1,
 
                                                not_empty=False)
rhodecode/model/notification.py
Show inline comments
 
@@ -19,64 +19,67 @@
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import os
 
import logging
 
import traceback
 

	
 
from pylons import tmpl_context as c
 
from pylons.i18n.translation import _
 

	
 
import rhodecode
 
from rhodecode.lib import helpers as h
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import Notification, User, UserNotification
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class NotificationModel(BaseModel):
 

	
 
    cls = Notification
 

	
 
    def __get_notification(self, notification):
 
        if isinstance(notification, Notification):
 
            return notification
 
        elif isinstance(notification, (int, long)):
 
            return Notification.get(notification)
 
        else:
 
            if notification:
 
                raise Exception('notification must be int, long or Instance'
 
                                ' of Notification got %s' % type(notification))
 

	
 
    def create(self, created_by, subject, body, recipients=None,
 
               type_=Notification.TYPE_MESSAGE, with_email=True,
 
               email_kwargs={}):
 
               email_kwargs={}, email_subject=None):
 
        """
 

	
 
        Creates notification of given type
 

	
 
        :param created_by: int, str or User instance. User who created this
 
            notification
 
        :param subject:
 
        :param body:
 
        :param recipients: list of int, str or User objects, when None
 
            is given send to all admins
 
        :param type_: type of notification
 
        :param with_email: send email with this notification
 
        :param email_kwargs: additional dict to pass as args to email template
 
        :param email_subject: use given subject as email subject
 
        """
 
        from rhodecode.lib.celerylib import tasks, run_task
 

	
 
        if recipients and not getattr(recipients, '__iter__', False):
 
            raise Exception('recipients must be a list or iterable')
 

	
 
        created_by_obj = self._get_user(created_by)
 

	
 
        if recipients:
 
            recipients_objs = []
 
            for u in recipients:
 
                obj = self._get_user(u)
 
@@ -96,61 +99,62 @@ class NotificationModel(BaseModel):
 
            created_by=created_by_obj, subject=subject,
 
            body=body, recipients=recipients_objs, type_=type_
 
        )
 

	
 
        if with_email is False:
 
            return notif
 

	
 
        #don't send email to person who created this comment
 
        rec_objs = set(recipients_objs).difference(set([created_by_obj]))
 

	
 
        # send email with notification to all other participants
 
        for rec in rec_objs:
 
            email_subject = NotificationModel().make_description(notif, False)
 
            if not email_subject:
 
                email_subject = NotificationModel()\
 
                                    .make_description(notif, show_age=False)
 
            type_ = type_
 
            email_body = body
 
            email_body = None  # we set body to none, we just send HTML emails
 
            ## this is passed into template
 
            kwargs = {'subject': subject, 'body': h.rst_w_mentions(body)}
 
            kwargs.update(email_kwargs)
 
            email_body_html = EmailNotificationModel()\
 
                                .get_email_tmpl(type_, **kwargs)
 

	
 
            run_task(tasks.send_email, rec.email, email_subject, email_body,
 
                     email_body_html)
 

	
 
        return notif
 

	
 
    def delete(self, user, notification):
 
        # we don't want to remove actual notification just the assignment
 
        try:
 
            notification = self.__get_notification(notification)
 
            user = self._get_user(user)
 
            if notification and user:
 
                obj = UserNotification.query()\
 
                        .filter(UserNotification.user == user)\
 
                        .filter(UserNotification.notification
 
                                == notification)\
 
                        .one()
 
                self.sa.delete(obj)
 
                Session().delete(obj)
 
                return True
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def get_for_user(self, user, filter_=None):
 
        """
 
        Get mentions for given user, filter them if filter dict is given
 

	
 
        :param user:
 
        :type user:
 
        :param filter:
 
        """
 
        user = self._get_user(user)
 

	
 
        q = UserNotification.query()\
 
            .filter(UserNotification.user == user)\
 
            .join((Notification, UserNotification.notification_id ==
 
                                 Notification.notification_id))
 

	
 
        if filter_:
 
            q = q.filter(Notification.type_.in_(filter_))
 

	
 
@@ -158,45 +162,45 @@ class NotificationModel(BaseModel):
 

	
 
    def mark_read(self, user, notification):
 
        try:
 
            notification = self.__get_notification(notification)
 
            user = self._get_user(user)
 
            if notification and user:
 
                obj = UserNotification.query()\
 
                        .filter(UserNotification.user == user)\
 
                        .filter(UserNotification.notification
 
                                == notification)\
 
                        .one()
 
                obj.read = True
 
                self.sa.add(obj)
 
                Session().add(obj)
 
                return True
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def mark_all_read_for_user(self, user, filter_=None):
 
        user = self._get_user(user)
 
        q = UserNotification.query()\
 
            .filter(UserNotification.user == user)\
 
            .filter(UserNotification.read == False)\
 
            .join((Notification, UserNotification.notification_id ==
 
                                 Notification.notification_id))
 
        if filter_:
 
            q = q.filter(Notification.type_.in_(filter_))
 

	
 
        # this is a little inefficient but sqlalchemy doesn't support
 
        # update on joined tables :(
 
        for obj in q.all():
 
            obj.read = True
 
            self.sa.add(obj)
 
            Session().add(obj)
 

	
 
    def get_unread_cnt_for_user(self, user):
 
        user = self._get_user(user)
 
        return UserNotification.query()\
 
                .filter(UserNotification.read == False)\
 
                .filter(UserNotification.user == user).count()
 

	
 
    def get_unread_for_user(self, user):
 
        user = self._get_user(user)
 
        return [x.notification for x in UserNotification.query()\
 
                .filter(UserNotification.read == False)\
 
                .filter(UserNotification.user == user).all()]
 
@@ -208,25 +212,25 @@ class NotificationModel(BaseModel):
 
        return UserNotification.query()\
 
            .filter(UserNotification.notification == notification)\
 
            .filter(UserNotification.user == user).scalar()
 

	
 
    def make_description(self, notification, show_age=True):
 
        """
 
        Creates a human readable description based on properties
 
        of notification object
 
        """
 
        #alias
 
        _n = notification
 
        _map = {
 
            _n.TYPE_CHANGESET_COMMENT: _('commented on commit at %(when)s'),
 
            _n.TYPE_CHANGESET_COMMENT: _('commented on changeset at %(when)s'),
 
            _n.TYPE_MESSAGE: _('sent message at %(when)s'),
 
            _n.TYPE_MENTION: _('mentioned you at %(when)s'),
 
            _n.TYPE_REGISTRATION: _('registered in RhodeCode at %(when)s'),
 
            _n.TYPE_PULL_REQUEST: _('opened new pull request at %(when)s'),
 
            _n.TYPE_PULL_REQUEST_COMMENT: _('commented on pull request at %(when)s')
 
        }
 

	
 
        # action == _map string
 
        tmpl = "%(user)s %(action)s "
 
        if show_age:
 
            when = h.age(notification.created_on)
 
        else:
 
@@ -263,16 +267,17 @@ class EmailNotificationModel(BaseModel):
 

	
 
    def get_email_tmpl(self, type_, **kwargs):
 
        """
 
        return generated template for email based on given type
 

	
 
        :param type_:
 
        """
 

	
 
        base = self.email_types.get(type_, self.email_types[self.TYPE_DEFAULT])
 
        email_template = self._tmpl_lookup.get_template(base)
 
        # translator and helpers inject
 
        _kwargs = {'_': _,
 
                   'h': h}
 
                   'h': h,
 
                   'c': c}
 
        _kwargs.update(kwargs)
 
        log.debug('rendering tmpl %s with kwargs %s' % (base, _kwargs))
 
        return email_template.render(**_kwargs)
rhodecode/model/pull_request.py
Show inline comments
 
@@ -66,64 +66,65 @@ class PullRequestModel(BaseModel):
 
        org_repo = self._get_repo(org_repo)
 
        other_repo = self._get_repo(other_repo)
 

	
 
        new = PullRequest()
 
        new.org_repo = org_repo
 
        new.org_ref = org_ref
 
        new.other_repo = other_repo
 
        new.other_ref = other_ref
 
        new.revisions = revisions
 
        new.title = title
 
        new.description = description
 
        new.author = created_by_user
 
        self.sa.add(new)
 
        Session().add(new)
 
        Session().flush()
 
        #members
 
        for member in set(reviewers):
 
            _usr = self._get_user(member)
 
            reviewer = PullRequestReviewers(_usr, new)
 
            self.sa.add(reviewer)
 
            Session().add(reviewer)
 

	
 
        #reset state to under-review
 
        ChangesetStatusModel().set_status(
 
            repo=org_repo,
 
            status=ChangesetStatus.STATUS_UNDER_REVIEW,
 
            user=created_by_user,
 
            pull_request=new
 
        )
 

	
 
        revision_data = [(x.raw_id, x.message)
 
                         for x in map(org_repo.get_changeset, revisions)]
 
        #notification to reviewers
 
        notif = NotificationModel()
 

	
 
        pr_url = h.url('pullrequest_show', repo_name=other_repo.repo_name,
 
                       pull_request_id=new.pull_request_id,
 
                       qualified=True,
 
        )
 
        subject = safe_unicode(
 
            h.link_to(
 
              _('%(user)s wants you to review pull request #%(pr_id)s: %(pr_title)s') % \
 
                {'user': created_by_user.username,
 
                 'pr_title': new.title,
 
                 'pr_id': new.pull_request_id},
 
                pr_url
 
            )
 
        )
 
        body = description
 
        kwargs = {
 
            'pr_title': title,
 
            'pr_user_created': h.person(created_by_user.email),
 
            'pr_repo_url': h.url('summary_home', repo_name=other_repo.repo_name,
 
                                 qualified=True,),
 
            'pr_url': pr_url,
 
            'pr_revisions': revisions
 
            'pr_revisions': revision_data
 
        }
 

	
 
        notif.create(created_by=created_by_user, subject=subject, body=body,
 
                     recipients=reviewers,
 
                     type_=Notification.TYPE_PULL_REQUEST, email_kwargs=kwargs)
 
        return new
 

	
 
    def update_reviewers(self, pull_request, reviewers_ids):
 
        reviewers_ids = set(reviewers_ids)
 
        pull_request = self.__get_pull_request(pull_request)
 
        current_reviewers = PullRequestReviewers.query()\
 
                            .filter(PullRequestReviewers.pull_request==
 
@@ -131,43 +132,43 @@ class PullRequestModel(BaseModel):
 
                            .all()
 
        current_reviewers_ids = set([x.user.user_id for x in current_reviewers])
 

	
 
        to_add = reviewers_ids.difference(current_reviewers_ids)
 
        to_remove = current_reviewers_ids.difference(reviewers_ids)
 

	
 
        log.debug("Adding %s reviewers" % to_add)
 
        log.debug("Removing %s reviewers" % to_remove)
 

	
 
        for uid in to_add:
 
            _usr = self._get_user(uid)
 
            reviewer = PullRequestReviewers(_usr, pull_request)
 
            self.sa.add(reviewer)
 
            Session().add(reviewer)
 

	
 
        for uid in to_remove:
 
            reviewer = PullRequestReviewers.query()\
 
                    .filter(PullRequestReviewers.user_id==uid,
 
                            PullRequestReviewers.pull_request==pull_request)\
 
                    .scalar()
 
            if reviewer:
 
                self.sa.delete(reviewer)
 
                Session().delete(reviewer)
 

	
 
    def delete(self, pull_request):
 
        pull_request = self.__get_pull_request(pull_request)
 
        Session().delete(pull_request)
 

	
 
    def close_pull_request(self, pull_request):
 
        pull_request = self.__get_pull_request(pull_request)
 
        pull_request.status = PullRequest.STATUS_CLOSED
 
        pull_request.updated_on = datetime.datetime.now()
 
        self.sa.add(pull_request)
 
        Session().add(pull_request)
 

	
 
    def _get_changesets(self, alias, org_repo, org_ref, other_repo, other_ref):
 
        """
 
        Returns a list of changesets that can be merged from org_repo@org_ref
 
        to other_repo@other_ref ... and the ancestor that would be used for merge
 

	
 
        :param org_repo:
 
        :param org_ref:
 
        :param other_repo:
 
        :param other_ref:
 
        :param tmp:
 
        """
 
@@ -239,20 +240,16 @@ class PullRequestModel(BaseModel):
 
        :param org_repo:
 
        :param org_ref:
 
        :param other_repo:
 
        :param other_ref:
 
        """
 

	
 
        if len(org_ref) != 2 or not isinstance(org_ref, (list, tuple)):
 
            raise Exception('org_ref must be a two element list/tuple')
 

	
 
        if len(other_ref) != 2 or not isinstance(org_ref, (list, tuple)):
 
            raise Exception('other_ref must be a two element list/tuple')
 

	
 
        org_repo_scm = org_repo.scm_instance
 
        other_repo_scm = other_repo.scm_instance
 

	
 
        alias = org_repo.scm_instance.alias
 
        cs_ranges, ancestor = self._get_changesets(alias,
 
                                                   org_repo_scm, org_ref,
 
                                                   other_repo_scm, other_ref)
 
        cs_ranges, ancestor = self._get_changesets(org_repo.scm_instance.alias,
 
                                                   org_repo.scm_instance, org_ref,
 
                                                   other_repo.scm_instance, other_ref)
 
        return cs_ranges, ancestor
rhodecode/model/repo.py
Show inline comments
 
@@ -29,42 +29,42 @@ import logging
 
import traceback
 
from datetime import datetime
 

	
 
from rhodecode.lib.vcs.backends import get_backend
 
from rhodecode.lib.compat import json
 
from rhodecode.lib.utils2 import LazyProperty, safe_str, safe_unicode,\
 
    remove_prefix
 
from rhodecode.lib.caching_query import FromCache
 
from rhodecode.lib.hooks import log_create_repository, log_delete_repository
 

	
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import Repository, UserRepoToPerm, User, Permission, \
 
    Statistics, UsersGroup, UsersGroupRepoToPerm, RhodeCodeUi, RepoGroup,\
 
    Statistics, UserGroup, UserGroupRepoToPerm, RhodeCodeUi, RepoGroup,\
 
    RhodeCodeSetting, RepositoryField
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import HasRepoPermissionAny
 
from rhodecode.lib.vcs.backends.base import EmptyChangeset
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepoModel(BaseModel):
 

	
 
    cls = Repository
 
    URL_SEPARATOR = Repository.url_sep()
 

	
 
    def __get_users_group(self, users_group):
 
        return self._get_instance(UsersGroup, users_group,
 
                                  callback=UsersGroup.get_by_group_name)
 
        return self._get_instance(UserGroup, users_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
 
    def _get_repos_group(self, repos_group):
 
        return self._get_instance(RepoGroup, repos_group,
 
                                  callback=RepoGroup.get_by_group_name)
 

	
 
    @LazyProperty
 
    def repos_path(self):
 
        """
 
        Get's the repositories root path from database
 
        """
 

	
 
        q = self.sa.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key == '/').one()
 
@@ -111,26 +111,26 @@ class RepoModel(BaseModel):
 
        users = self.sa.query(User).filter(User.active == True).all()
 
        return json.dumps([
 
            {
 
             'id': u.user_id,
 
             'fname': u.name,
 
             'lname': u.lastname,
 
             'nname': u.username,
 
             'gravatar_lnk': h.gravatar_url(u.email, 14)
 
            } for u in users]
 
        )
 

	
 
    def get_users_groups_js(self):
 
        users_groups = self.sa.query(UsersGroup)\
 
            .filter(UsersGroup.users_group_active == True).all()
 
        users_groups = self.sa.query(UserGroup)\
 
            .filter(UserGroup.users_group_active == True).all()
 

	
 
        return json.dumps([
 
            {
 
             'id': gr.users_group_id,
 
             'grname': gr.users_group_name,
 
             'grmembers': len(gr.members),
 
            } for gr in users_groups]
 
        )
 

	
 
    @classmethod
 
    def _render_datatable(cls, tmpl, *args, **kwargs):
 
        import rhodecode
 
@@ -140,29 +140,25 @@ class RepoModel(BaseModel):
 
        _tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup
 
        template = _tmpl_lookup.get_template('data_table/_dt_elements.html')
 

	
 
        tmpl = template.get_def(tmpl)
 
        kwargs.update(dict(_=_, h=h, c=c))
 
        return tmpl.render(*args, **kwargs)
 

	
 
    @classmethod
 
    def update_repoinfo(cls, repositories=None):
 
        if not repositories:
 
            repositories = Repository.getAll()
 
        for repo in repositories:
 
            scm_repo = repo.scm_instance_no_cache
 
            last_cs = EmptyChangeset()
 
            if scm_repo:
 
                last_cs = scm_repo.get_changeset()
 
            repo.update_changeset_cache(last_cs)
 
            repo.update_changeset_cache()
 

	
 
    def get_repos_as_dict(self, repos_list=None, admin=False, perm_check=True,
 
                          super_user_actions=False):
 
        _render = self._render_datatable
 

	
 
        def quick_menu(repo_name):
 
            return _render('quick_menu', repo_name)
 

	
 
        def repo_lnk(name, rtype, private, fork_of):
 
            return _render('repo_name', name, rtype, private, fork_of,
 
                           short_name=not admin, admin=False)
 

	
 
@@ -406,33 +402,33 @@ class RepoModel(BaseModel):
 
                        .one().permission_id
 

	
 
                repo_to_perm.repository = new_repo
 
                repo_to_perm.user_id = User.get_by_username('default').user_id
 

	
 
                self.sa.add(repo_to_perm)
 

	
 
            if fork_of:
 
                if copy_fork_permissions:
 
                    repo = fork_of
 
                    user_perms = UserRepoToPerm.query()\
 
                        .filter(UserRepoToPerm.repository == repo).all()
 
                    group_perms = UsersGroupRepoToPerm.query()\
 
                        .filter(UsersGroupRepoToPerm.repository == repo).all()
 
                    group_perms = UserGroupRepoToPerm.query()\
 
                        .filter(UserGroupRepoToPerm.repository == repo).all()
 

	
 
                    for perm in user_perms:
 
                        UserRepoToPerm.create(perm.user, new_repo,
 
                                              perm.permission)
 

	
 
                    for perm in group_perms:
 
                        UsersGroupRepoToPerm.create(perm.users_group, new_repo,
 
                        UserGroupRepoToPerm.create(perm.users_group, new_repo,
 
                                                    perm.permission)
 
                else:
 
                    _create_default_perms()
 
            else:
 
                _create_default_perms()
 

	
 
            if not just_db:
 
                self.__create_repo(repo_name, repo_type,
 
                                   repos_group,
 
                                   clone_uri)
 
                log_create_repository(new_repo.get_dict(),
 
                                      created_by=owner.username)
 
@@ -540,66 +536,66 @@ class RepoModel(BaseModel):
 
        repo = self._get_repo(repo)
 

	
 
        obj = self.sa.query(UserRepoToPerm)\
 
            .filter(UserRepoToPerm.repository == repo)\
 
            .filter(UserRepoToPerm.user == user)\
 
            .scalar()
 
        if obj:
 
            self.sa.delete(obj)
 
            log.debug('Revoked perm on %s on %s' % (repo, user))
 

	
 
    def grant_users_group_permission(self, repo, group_name, perm):
 
        """
 
        Grant permission for users group on given repository, or update
 
        Grant permission for user group on given repository, or update
 
        existing one if found
 

	
 
        :param repo: Instance of Repository, repository_id, or repository name
 
        :param group_name: Instance of UserGroup, users_group_id,
 
            or users group name
 
            or user group name
 
        :param perm: Instance of Permission, or permission_name
 
        """
 
        repo = self._get_repo(repo)
 
        group_name = self.__get_users_group(group_name)
 
        permission = self._get_perm(perm)
 

	
 
        # check if we have that permission already
 
        obj = self.sa.query(UsersGroupRepoToPerm)\
 
            .filter(UsersGroupRepoToPerm.users_group == group_name)\
 
            .filter(UsersGroupRepoToPerm.repository == repo)\
 
        obj = self.sa.query(UserGroupRepoToPerm)\
 
            .filter(UserGroupRepoToPerm.users_group == group_name)\
 
            .filter(UserGroupRepoToPerm.repository == repo)\
 
            .scalar()
 

	
 
        if obj is None:
 
            # create new
 
            obj = UsersGroupRepoToPerm()
 
            obj = UserGroupRepoToPerm()
 

	
 
        obj.repository = repo
 
        obj.users_group = group_name
 
        obj.permission = permission
 
        self.sa.add(obj)
 
        log.debug('Granted perm %s to %s on %s' % (perm, group_name, repo))
 

	
 
    def revoke_users_group_permission(self, repo, group_name):
 
        """
 
        Revoke permission for users group on given repository
 
        Revoke permission for user group on given repository
 

	
 
        :param repo: Instance of Repository, repository_id, or repository name
 
        :param group_name: Instance of UserGroup, users_group_id,
 
            or users group name
 
            or user group name
 
        """
 
        repo = self._get_repo(repo)
 
        group_name = self.__get_users_group(group_name)
 

	
 
        obj = self.sa.query(UsersGroupRepoToPerm)\
 
            .filter(UsersGroupRepoToPerm.repository == repo)\
 
            .filter(UsersGroupRepoToPerm.users_group == group_name)\
 
        obj = self.sa.query(UserGroupRepoToPerm)\
 
            .filter(UserGroupRepoToPerm.repository == repo)\
 
            .filter(UserGroupRepoToPerm.users_group == group_name)\
 
            .scalar()
 
        if obj:
 
            self.sa.delete(obj)
 
            log.debug('Revoked perm to %s on %s' % (repo, group_name))
 

	
 
    def delete_stats(self, repo_name):
 
        """
 
        removes stats for given repo
 

	
 
        :param repo_name:
 
        """
 
        repo = self._get_repo(repo_name)
rhodecode/model/repo_permission.py
Show inline comments
 
@@ -17,25 +17,25 @@
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import UserRepoToPerm, UsersGroupRepoToPerm, \
 
from rhodecode.model.db import UserRepoToPerm, UserGroupRepoToPerm, \
 
    Permission
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class RepositoryPermissionModel(BaseModel):
 

	
 
    cls = UserRepoToPerm
 

	
 
    def get_user_permission(self, repository, user):
 
        repository = self._get_repo(repository)
 
        user = self._get_user(user)
 
@@ -55,38 +55,38 @@ class RepositoryPermissionModel(BaseMode
 
            p = UserRepoToPerm()
 
            p.user = user
 
            p.repository = repository
 
            p.permission = permission
 
            self.sa.add(p)
 

	
 
    def delete_user_permission(self, repository, user):
 
        current = self.get_user_permission(repository, user)
 
        if current:
 
            self.sa.delete(current)
 

	
 
    def get_users_group_permission(self, repository, users_group):
 
        return UsersGroupRepoToPerm.query() \
 
                .filter(UsersGroupRepoToPerm.users_group == users_group) \
 
                .filter(UsersGroupRepoToPerm.repository == repository) \
 
        return UserGroupRepoToPerm.query() \
 
                .filter(UserGroupRepoToPerm.users_group == users_group) \
 
                .filter(UserGroupRepoToPerm.repository == repository) \
 
                .scalar()
 

	
 
    def update_users_group_permission(self, repository, users_group,
 
                                      permission):
 
        permission = Permission.get_by_key(permission)
 
        current = self.get_users_group_permission(repository, users_group)
 
        if current:
 
            if not current.permission is permission:
 
                current.permission = permission
 
        else:
 
            p = UsersGroupRepoToPerm()
 
            p = UserGroupRepoToPerm()
 
            p.users_group = users_group
 
            p.repository = repository
 
            p.permission = permission
 
            self.sa.add(p)
 

	
 
    def delete_users_group_permission(self, repository, users_group):
 
        current = self.get_users_group_permission(repository, users_group)
 
        if current:
 
            self.sa.delete(current)
 

	
 
    def update_or_delete_user_permission(self, repository, user, permission):
 
        if permission:
rhodecode/model/repos_group.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.model.user_group
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    users groups model for RhodeCode
 
    repo group model for RhodeCode
 

	
 
    :created_on: Jan 25, 2011
 
    :author: marcink
 
    :copyright: (C) 2011-2012 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
@@ -24,36 +24,36 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import os
 
import logging
 
import traceback
 
import shutil
 
import datetime
 

	
 
from rhodecode.lib.utils2 import LazyProperty
 

	
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import RepoGroup, RhodeCodeUi, UserRepoGroupToPerm, \
 
    User, Permission, UsersGroupRepoGroupToPerm, UsersGroup, Repository
 
    User, Permission, UserGroupRepoGroupToPerm, UserGroup, Repository
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ReposGroupModel(BaseModel):
 

	
 
    cls = RepoGroup
 

	
 
    def __get_users_group(self, users_group):
 
        return self._get_instance(UsersGroup, users_group,
 
                                  callback=UsersGroup.get_by_group_name)
 
        return self._get_instance(UserGroup, users_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
 
    def _get_repos_group(self, repos_group):
 
        return self._get_instance(RepoGroup, repos_group,
 
                                  callback=RepoGroup.get_by_group_name)
 

	
 
    @LazyProperty
 
    def repos_path(self):
 
        """
 
        Get's the repositories root path from database
 
        """
 

	
 
        q = RhodeCodeUi.get_by_key('/')
 
@@ -70,25 +70,25 @@ class ReposGroupModel(BaseModel):
 

	
 
        repo_group_to_perm.permission_id = self.sa.query(Permission)\
 
                .filter(Permission.permission_name == default_perm)\
 
                .one().permission_id
 

	
 
        repo_group_to_perm.group = new_group
 
        repo_group_to_perm.user_id = User.get_by_username('default').user_id
 

	
 
        self.sa.add(repo_group_to_perm)
 

	
 
    def __create_group(self, group_name):
 
        """
 
        makes repositories group on filesystem
 
        makes repository group on filesystem
 

	
 
        :param repo_name:
 
        :param parent_id:
 
        """
 

	
 
        create_path = os.path.join(self.repos_path, group_name)
 
        log.debug('creating new group in %s' % create_path)
 

	
 
        if os.path.isdir(create_path):
 
            raise Exception('That directory already exists !')
 

	
 
        os.makedirs(create_path)
 
@@ -209,25 +209,25 @@ class ReposGroupModel(BaseModel):
 

	
 
        for obj in repos_group.recursive_groups_and_repos():
 
            #obj is an instance of a group or repositories in that group
 
            if not recursive:
 
                obj = repos_group
 

	
 
            # update permissions
 
            for member, perm, member_type in perms_updates:
 
                ## set for user
 
                if member_type == 'user':
 
                    # this updates also current one if found
 
                    _set_perm_user(obj, user=member, perm=perm)
 
                ## set for users group
 
                ## set for user group
 
                else:
 
                    _set_perm_group(obj, users_group=member, perm=perm)
 
            # set new permissions
 
            for member, perm, member_type in perms_new:
 
                if member_type == 'user':
 
                    _set_perm_user(obj, user=member, perm=perm)
 
                else:
 
                    _set_perm_group(obj, users_group=member, perm=perm)
 
            updates.append(obj)
 
            #if it's not recursive call
 
            # break the loop and don't proceed with other changes
 
            if not recursive:
 
@@ -280,29 +280,29 @@ class ReposGroupModel(BaseModel):
 
    def delete(self, repos_group, force_delete=False):
 
        repos_group = self._get_repos_group(repos_group)
 
        try:
 
            self.sa.delete(repos_group)
 
            self.__delete_group(repos_group, force_delete)
 
        except:
 
            log.error('Error removing repos_group %s' % repos_group)
 
            raise
 

	
 
    def delete_permission(self, repos_group, obj, obj_type, recursive):
 
        """
 
        Revokes permission for repos_group for given obj(user or users_group),
 
        obj_type can be user or users group
 
        obj_type can be user or user group
 

	
 
        :param repos_group:
 
        :param obj: user or users group id
 
        :param obj_type: user or users group type
 
        :param obj: user or user group id
 
        :param obj_type: user or user group type
 
        :param recursive: recurse to all children of group
 
        """
 
        from rhodecode.model.repo import RepoModel
 
        repos_group = self._get_repos_group(repos_group)
 

	
 
        for el in repos_group.recursive_groups_and_repos():
 
            if not recursive:
 
                # if we don't recurse set the permission on only the top level
 
                # object
 
                el = repos_group
 

	
 
            if isinstance(el, RepoGroup):
 
@@ -318,25 +318,25 @@ class ReposGroupModel(BaseModel):
 
                elif obj_type == 'users_group':
 
                    RepoModel().revoke_users_group_permission(el, group_name=obj)
 
                else:
 
                    raise Exception('undefined object type %s' % obj_type)
 

	
 
            #if it's not recursive call
 
            # break the loop and don't proceed with other changes
 
            if not recursive:
 
                break
 

	
 
    def grant_user_permission(self, repos_group, user, perm):
 
        """
 
        Grant permission for user on given repositories group, or update
 
        Grant permission for user on given repository group, or update
 
        existing one if found
 

	
 
        :param repos_group: Instance of ReposGroup, repositories_group_id,
 
            or repositories_group name
 
        :param user: Instance of User, user_id or username
 
        :param perm: Instance of Permission, or permission_name
 
        """
 

	
 
        repos_group = self._get_repos_group(repos_group)
 
        user = self._get_user(user)
 
        permission = self._get_perm(perm)
 

	
 
@@ -347,80 +347,80 @@ class ReposGroupModel(BaseModel):
 
            .scalar()
 
        if obj is None:
 
            # create new !
 
            obj = UserRepoGroupToPerm()
 
        obj.group = repos_group
 
        obj.user = user
 
        obj.permission = permission
 
        self.sa.add(obj)
 
        log.debug('Granted perm %s to %s on %s' % (perm, user, repos_group))
 

	
 
    def revoke_user_permission(self, repos_group, user):
 
        """
 
        Revoke permission for user on given repositories group
 
        Revoke permission for user on given repository group
 

	
 
        :param repos_group: Instance of ReposGroup, repositories_group_id,
 
            or repositories_group name
 
        :param user: Instance of User, user_id or username
 
        """
 

	
 
        repos_group = self._get_repos_group(repos_group)
 
        user = self._get_user(user)
 

	
 
        obj = self.sa.query(UserRepoGroupToPerm)\
 
            .filter(UserRepoGroupToPerm.user == user)\
 
            .filter(UserRepoGroupToPerm.group == repos_group)\
 
            .scalar()
 
        if obj:
 
            self.sa.delete(obj)
 
            log.debug('Revoked perm on %s on %s' % (repos_group, user))
 

	
 
    def grant_users_group_permission(self, repos_group, group_name, perm):
 
        """
 
        Grant permission for users group on given repositories group, or update
 
        Grant permission for user group on given repository group, or update
 
        existing one if found
 

	
 
        :param repos_group: Instance of ReposGroup, repositories_group_id,
 
            or repositories_group name
 
        :param group_name: Instance of UserGroup, users_group_id,
 
            or users group name
 
            or user group name
 
        :param perm: Instance of Permission, or permission_name
 
        """
 
        repos_group = self._get_repos_group(repos_group)
 
        group_name = self.__get_users_group(group_name)
 
        permission = self._get_perm(perm)
 

	
 
        # check if we have that permission already
 
        obj = self.sa.query(UsersGroupRepoGroupToPerm)\
 
            .filter(UsersGroupRepoGroupToPerm.group == repos_group)\
 
            .filter(UsersGroupRepoGroupToPerm.users_group == group_name)\
 
        obj = self.sa.query(UserGroupRepoGroupToPerm)\
 
            .filter(UserGroupRepoGroupToPerm.group == repos_group)\
 
            .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
 
            .scalar()
 

	
 
        if obj is None:
 
            # create new
 
            obj = UsersGroupRepoGroupToPerm()
 
            obj = UserGroupRepoGroupToPerm()
 

	
 
        obj.group = repos_group
 
        obj.users_group = group_name
 
        obj.permission = permission
 
        self.sa.add(obj)
 
        log.debug('Granted perm %s to %s on %s' % (perm, group_name, repos_group))
 

	
 
    def revoke_users_group_permission(self, repos_group, group_name):
 
        """
 
        Revoke permission for users group on given repositories group
 
        Revoke permission for user group on given repository group
 

	
 
        :param repos_group: Instance of ReposGroup, repositories_group_id,
 
            or repositories_group name
 
        :param group_name: Instance of UserGroup, users_group_id,
 
            or users group name
 
            or user group name
 
        """
 
        repos_group = self._get_repos_group(repos_group)
 
        group_name = self.__get_users_group(group_name)
 

	
 
        obj = self.sa.query(UsersGroupRepoGroupToPerm)\
 
            .filter(UsersGroupRepoGroupToPerm.group == repos_group)\
 
            .filter(UsersGroupRepoGroupToPerm.users_group == group_name)\
 
        obj = self.sa.query(UserGroupRepoGroupToPerm)\
 
            .filter(UserGroupRepoGroupToPerm.group == repos_group)\
 
            .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
 
            .scalar()
 
        if obj:
 
            self.sa.delete(obj)
 
            log.debug('Revoked perm to %s on %s' % (repos_group, group_name))
rhodecode/model/scm.py
Show inline comments
 
@@ -282,27 +282,25 @@ class ScmModel(BaseModel):
 
                                             order_by=sort_key)
 
        else:
 
            repo_iter = CachedRepoList(all_repos,
 
                                       repos_path=self.repos_path,
 
                                       order_by=sort_key)
 

	
 
        return repo_iter
 

	
 
    def get_repos_groups(self, all_groups=None):
 
        if all_groups is None:
 
            all_groups = RepoGroup.query()\
 
                .filter(RepoGroup.group_parent_id == None).all()
 
        group_iter = GroupList(all_groups)
 

	
 
        return group_iter
 
        return [x for x in GroupList(all_groups)]
 

	
 
    def mark_for_invalidation(self, repo_name):
 
        """
 
        Puts cache invalidation task into db for
 
        further global cache invalidation
 

	
 
        :param repo_name: this repo that should invalidation take place
 
        """
 
        invalidated_keys = CacheInvalidation.set_invalidate(repo_name=repo_name)
 
        repo = Repository.get_by_repo_name(repo_name)
 
        if repo:
 
            repo.update_changeset_cache()
rhodecode/model/user.py
Show inline comments
 
@@ -28,29 +28,30 @@ import traceback
 
import itertools
 
import collections
 
from pylons import url
 
from pylons.i18n.translation import _
 

	
 
from sqlalchemy.exc import DatabaseError
 
from sqlalchemy.orm import joinedload
 

	
 
from rhodecode.lib.utils2 import safe_unicode, generate_api_key
 
from rhodecode.lib.caching_query import FromCache
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import User, UserRepoToPerm, Repository, Permission, \
 
    UserToPerm, UsersGroupRepoToPerm, UsersGroupToPerm, UsersGroupMember, \
 
    Notification, RepoGroup, UserRepoGroupToPerm, UsersGroupRepoGroupToPerm, \
 
    UserToPerm, UserGroupRepoToPerm, UserGroupToPerm, UserGroupMember, \
 
    Notification, RepoGroup, UserRepoGroupToPerm, UserGroupRepoGroupToPerm, \
 
    UserEmailMap, UserIpMap
 
from rhodecode.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
from rhodecode.model.meta import Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 
PERM_WEIGHTS = Permission.PERM_WEIGHTS
 

	
 

	
 
class UserModel(BaseModel):
 
    cls = User
 

	
 
    def get(self, user_id, cache=False):
 
        user = self.sa.query(User)
 
@@ -307,29 +308,79 @@ class UserModel(BaseModel):
 
                raise UserOwnsReposException(
 
                    _(u'user "%s" still owns %s repositories and cannot be '
 
                      'removed. Switch owners or remove those repositories. %s')
 
                    % (user.username, len(repos), ', '.join(repos))
 
                )
 
            self.sa.delete(user)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def reset_password_link(self, data):
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        run_task(tasks.send_password_link, data['email'])
 
        from rhodecode.model.notification import EmailNotificationModel
 
        user_email = data['email']
 
        try:
 
            user = User.get_by_email(user_email)
 
            if user:
 
                log.debug('password reset user found %s' % user)
 
                link = url('reset_password_confirmation', key=user.api_key,
 
                           qualified=True)
 
                reg_type = EmailNotificationModel.TYPE_PASSWORD_RESET
 
                body = EmailNotificationModel().get_email_tmpl(reg_type,
 
                                                    **{'user': user.short_contact,
 
                                                       'reset_url': link})
 
                log.debug('sending email')
 
                run_task(tasks.send_email, user_email,
 
                         _("password reset link"), body, body)
 
                log.info('send new password mail to %s' % user_email)
 
            else:
 
                log.debug("password reset email %s not found" % user_email)
 
        except:
 
            log.error(traceback.format_exc())
 
            return False
 

	
 
        return True
 

	
 
    def reset_password(self, data):
 
        from rhodecode.lib.celerylib import tasks, run_task
 
        run_task(tasks.reset_user_password, data['email'])
 
        from rhodecode.lib import auth
 
        user_email = data['email']
 
        try:
 
            try:
 
                user = User.get_by_email(user_email)
 
                new_passwd = auth.PasswordGenerator().gen_password(8,
 
                                 auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
 
                if user:
 
                    user.password = auth.get_crypt_password(new_passwd)
 
                    user.api_key = auth.generate_api_key(user.username)
 
                    Session().add(user)
 
                    Session().commit()
 
                    log.info('change password for %s' % user_email)
 
                if new_passwd is None:
 
                    raise Exception('unable to generate new password')
 
            except:
 
                log.error(traceback.format_exc())
 
                Session().rollback()
 

	
 
            run_task(tasks.send_email, user_email,
 
                     _('Your new password'),
 
                     _('Your new RhodeCode password:%s') % (new_passwd))
 
            log.info('send new password mail to %s' % user_email)
 

	
 
        except:
 
            log.error('Failed to update user password')
 
            log.error(traceback.format_exc())
 

	
 
        return True
 

	
 
    def fill_data(self, auth_user, user_id=None, api_key=None):
 
        """
 
        Fetches auth_user by user_id,or api_key if present.
 
        Fills auth_user attributes with those taken from database.
 
        Additionally set's is_authenitated if lookup fails
 
        present in database
 

	
 
        :param auth_user: instance of user to set attributes
 
        :param user_id: user id to fetch by
 
        :param api_key: api key to fetch by
 
        """
 
@@ -404,25 +455,25 @@ class UserModel(BaseModel):
 
            #==================================================================
 
            # admin user have all default rights for repositories
 
            # and groups set to admin
 
            #==================================================================
 
            user.permissions[GLOBAL].add('hg.admin')
 

	
 
            # repositories
 
            for perm in default_repo_perms:
 
                r_k = perm.UserRepoToPerm.repository.repo_name
 
                p = 'repository.admin'
 
                user.permissions[RK][r_k] = p
 

	
 
            # repositories groups
 
            # repository groups
 
            for perm in default_repo_groups_perms:
 
                rg_k = perm.UserRepoGroupToPerm.group.group_name
 
                p = 'group.admin'
 
                user.permissions[GK][rg_k] = p
 
            return user
 

	
 
        #==================================================================
 
        # SET DEFAULTS GLOBAL, REPOS, REPOS GROUPS
 
        #==================================================================
 
        uid = user.user_id
 

	
 
        # default global permissions taken fron the default user
 
@@ -437,46 +488,46 @@ class UserModel(BaseModel):
 
            r_k = perm.UserRepoToPerm.repository.repo_name
 
            if perm.Repository.private and not (perm.Repository.user_id == uid):
 
                # disable defaults for private repos,
 
                p = 'repository.none'
 
            elif perm.Repository.user_id == uid:
 
                # set admin if owner
 
                p = 'repository.admin'
 
            else:
 
                p = perm.Permission.permission_name
 

	
 
            user.permissions[RK][r_k] = p
 

	
 
        # defaults for repositories groups taken from default user permission
 
        # defaults for repository groups taken from default user permission
 
        # on given group
 
        for perm in default_repo_groups_perms:
 
            rg_k = perm.UserRepoGroupToPerm.group.group_name
 
            p = perm.Permission.permission_name
 
            user.permissions[GK][rg_k] = p
 

	
 
        #======================================================================
 
        # !! OVERRIDE GLOBALS !! with user permissions if any found
 
        #======================================================================
 
        # those can be configured from groups or users explicitly
 
        _configurable = set(['hg.fork.none', 'hg.fork.repository',
 
                             'hg.create.none', 'hg.create.repository'])
 

	
 
        # USER GROUPS comes first
 
        # users group global permissions
 
        user_perms_from_users_groups = self.sa.query(UsersGroupToPerm)\
 
            .options(joinedload(UsersGroupToPerm.permission))\
 
            .join((UsersGroupMember, UsersGroupToPerm.users_group_id ==
 
                   UsersGroupMember.users_group_id))\
 
            .filter(UsersGroupMember.user_id == uid)\
 
            .order_by(UsersGroupToPerm.users_group_id)\
 
        # user group global permissions
 
        user_perms_from_users_groups = self.sa.query(UserGroupToPerm)\
 
            .options(joinedload(UserGroupToPerm.permission))\
 
            .join((UserGroupMember, UserGroupToPerm.users_group_id ==
 
                   UserGroupMember.users_group_id))\
 
            .filter(UserGroupMember.user_id == uid)\
 
            .order_by(UserGroupToPerm.users_group_id)\
 
            .all()
 
        #need to group here by groups since user can be in more than one group
 
        _grouped = [[x, list(y)] for x, y in
 
                    itertools.groupby(user_perms_from_users_groups,
 
                                      lambda x:x.users_group)]
 
        for gr, perms in _grouped:
 
            # since user can be in multiple groups iterate over them and
 
            # select the lowest permissions first (more explicit)
 
            ##TODO: do this^^
 
            if not gr.inherit_default_permissions:
 
                # NEED TO IGNORE all configurable permissions and
 
                # replace them with explicitly set
 
@@ -499,39 +550,39 @@ class UserModel(BaseModel):
 
            for perm in user_perms:
 
                user.permissions[GLOBAL].add(perm.permission.permission_name)
 

	
 
        #======================================================================
 
        # !! PERMISSIONS FOR REPOSITORIES !!
 
        #======================================================================
 
        #======================================================================
 
        # check if user is part of user groups for this repository and
 
        # fill in his permission from it. _choose_perm decides of which
 
        # permission should be selected based on selected method
 
        #======================================================================
 

	
 
        # users group for repositories permissions
 
        # user group for repositories permissions
 
        user_repo_perms_from_users_groups = \
 
         self.sa.query(UsersGroupRepoToPerm, Permission, Repository,)\
 
            .join((Repository, UsersGroupRepoToPerm.repository_id ==
 
         self.sa.query(UserGroupRepoToPerm, Permission, Repository,)\
 
            .join((Repository, UserGroupRepoToPerm.repository_id ==
 
                   Repository.repo_id))\
 
            .join((Permission, UsersGroupRepoToPerm.permission_id ==
 
            .join((Permission, UserGroupRepoToPerm.permission_id ==
 
                   Permission.permission_id))\
 
            .join((UsersGroupMember, UsersGroupRepoToPerm.users_group_id ==
 
                   UsersGroupMember.users_group_id))\
 
            .filter(UsersGroupMember.user_id == uid)\
 
            .join((UserGroupMember, UserGroupRepoToPerm.users_group_id ==
 
                   UserGroupMember.users_group_id))\
 
            .filter(UserGroupMember.user_id == uid)\
 
            .all()
 

	
 
        multiple_counter = collections.defaultdict(int)
 
        for perm in user_repo_perms_from_users_groups:
 
            r_k = perm.UsersGroupRepoToPerm.repository.repo_name
 
            r_k = perm.UserGroupRepoToPerm.repository.repo_name
 
            multiple_counter[r_k] += 1
 
            p = perm.Permission.permission_name
 
            cur_perm = user.permissions[RK][r_k]
 

	
 
            if perm.Repository.user_id == uid:
 
                # set admin if owner
 
                p = 'repository.admin'
 
            else:
 
                if multiple_counter[r_k] > 1:
 
                    p = _choose_perm(p, cur_perm)
 
            user.permissions[RK][r_k] = p
 

	
 
@@ -550,45 +601,45 @@ class UserModel(BaseModel):
 
            r_k = perm.UserRepoToPerm.repository.repo_name
 
            cur_perm = user.permissions[RK][r_k]
 
            # set admin if owner
 
            if perm.Repository.user_id == uid:
 
                p = 'repository.admin'
 
            else:
 
                p = perm.Permission.permission_name
 
                if not explicit:
 
                    p = _choose_perm(p, cur_perm)
 
            user.permissions[RK][r_k] = p
 

	
 
        #======================================================================
 
        # !! PERMISSIONS FOR REPOSITORIES GROUPS !!
 
        # !! PERMISSIONS FOR REPOSITORY GROUPS !!
 
        #======================================================================
 
        #======================================================================
 
        # check if user is part of user groups for this repository groups and
 
        # fill in his permission from it. _choose_perm decides of which
 
        # permission should be selected based on selected method
 
        #======================================================================
 
        # users group for repo groups permissions
 
        # user group for repo groups permissions
 
        user_repo_group_perms_from_users_groups = \
 
         self.sa.query(UsersGroupRepoGroupToPerm, Permission, RepoGroup)\
 
         .join((RepoGroup, UsersGroupRepoGroupToPerm.group_id == RepoGroup.group_id))\
 
         .join((Permission, UsersGroupRepoGroupToPerm.permission_id
 
         self.sa.query(UserGroupRepoGroupToPerm, Permission, RepoGroup)\
 
         .join((RepoGroup, UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id))\
 
         .join((Permission, UserGroupRepoGroupToPerm.permission_id
 
                == Permission.permission_id))\
 
         .join((UsersGroupMember, UsersGroupRepoGroupToPerm.users_group_id
 
                == UsersGroupMember.users_group_id))\
 
         .filter(UsersGroupMember.user_id == uid)\
 
         .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id
 
                == UserGroupMember.users_group_id))\
 
         .filter(UserGroupMember.user_id == uid)\
 
         .all()
 

	
 
        multiple_counter = collections.defaultdict(int)
 
        for perm in user_repo_group_perms_from_users_groups:
 
            g_k = perm.UsersGroupRepoGroupToPerm.group.group_name
 
            g_k = perm.UserGroupRepoGroupToPerm.group.group_name
 
            multiple_counter[g_k] += 1
 
            p = perm.Permission.permission_name
 
            cur_perm = user.permissions[GK][g_k]
 
            if multiple_counter[g_k] > 1:
 
                p = _choose_perm(p, cur_perm)
 
            user.permissions[GK][g_k] = p
 

	
 
        # user explicit permissions for repository groups
 
        user_repo_groups_perms = \
 
         self.sa.query(UserRepoGroupToPerm, Permission, RepoGroup)\
 
         .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
 
         .join((Permission, UserRepoGroupToPerm.permission_id
rhodecode/model/users_group.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.model.users_group
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    users group model for RhodeCode
 
    user group model for RhodeCode
 

	
 
    :created_on: Oct 1, 2011
 
    :author: nvinot
 
    :copyright: (C) 2011-2011 Nicolas Vinot <aeris@imirhil.fr>
 
    :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import logging
 
import traceback
 

	
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import UsersGroupMember, UsersGroup,\
 
    UsersGroupRepoToPerm, Permission, UsersGroupToPerm, User
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 
from rhodecode.model.db import UserGroupMember, UserGroup,\
 
    UserGroupRepoToPerm, Permission, UserGroupToPerm, User
 
from rhodecode.lib.exceptions import UserGroupsAssignedException
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersGroupModel(BaseModel):
 
class UserGroupModel(BaseModel):
 

	
 
    cls = UsersGroup
 
    cls = UserGroup
 

	
 
    def __get_users_group(self, users_group):
 
        return self._get_instance(UsersGroup, users_group,
 
                                  callback=UsersGroup.get_by_group_name)
 
        return self._get_instance(UserGroup, users_group,
 
                                  callback=UserGroup.get_by_group_name)
 

	
 
    def get(self, users_group_id, cache=False):
 
        return UsersGroup.get(users_group_id)
 
        return UserGroup.get(users_group_id)
 

	
 
    def get_group(self, users_group):
 
        return self.__get_users_group(users_group)
 

	
 
    def get_by_name(self, name, cache=False, case_insensitive=False):
 
        return UsersGroup.get_by_group_name(name, cache, case_insensitive)
 
        return UserGroup.get_by_group_name(name, cache, case_insensitive)
 

	
 
    def create(self, name, active=True):
 
        try:
 
            new = UsersGroup()
 
            new = UserGroup()
 
            new.users_group_name = name
 
            new.users_group_active = active
 
            self.sa.add(new)
 
            return new
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def update(self, users_group, form_data):
 

	
 
        try:
 
            users_group = self.__get_users_group(users_group)
 

	
 
            for k, v in form_data.items():
 
                if k == 'users_group_members':
 
                    users_group.members = []
 
                    self.sa.flush()
 
                    members_list = []
 
                    if v:
 
                        v = [v] if isinstance(v, basestring) else v
 
                        for u_id in set(v):
 
                            member = UsersGroupMember(users_group.users_group_id, u_id)
 
                            member = UserGroupMember(users_group.users_group_id, u_id)
 
                            members_list.append(member)
 
                    setattr(users_group, 'members', members_list)
 
                setattr(users_group, k, v)
 

	
 
            self.sa.add(users_group)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def delete(self, users_group, force=False):
 
        """
 
        Deletes repos group, unless force flag is used
 
        raises exception if there are members in that group, else deletes
 
        group and users
 

	
 
        :param users_group:
 
        :param force:
 
        """
 
        try:
 
            users_group = self.__get_users_group(users_group)
 

	
 
            # check if this group is not assigned to repo
 
            assigned_groups = UsersGroupRepoToPerm.query()\
 
                .filter(UsersGroupRepoToPerm.users_group == users_group).all()
 
            assigned_groups = UserGroupRepoToPerm.query()\
 
                .filter(UserGroupRepoToPerm.users_group == users_group).all()
 

	
 
            if assigned_groups and force is False:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                raise UserGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 

	
 
            self.sa.delete(users_group)
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def add_user_to_group(self, users_group, user):
 
        users_group = self.__get_users_group(users_group)
 
        user = self._get_user(user)
 

	
 
        for m in users_group.members:
 
            u = m.user
 
            if u.user_id == user.user_id:
 
                return True
 

	
 
        try:
 
            users_group_member = UsersGroupMember()
 
            users_group_member = UserGroupMember()
 
            users_group_member.user = user
 
            users_group_member.users_group = users_group
 

	
 
            users_group.members.append(users_group_member)
 
            user.group_member.append(users_group_member)
 

	
 
            self.sa.add(users_group_member)
 
            return users_group_member
 
        except:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
@@ -151,42 +151,42 @@ class UsersGroupModel(BaseModel):
 
                return True
 
            except:
 
                log.error(traceback.format_exc())
 
                raise
 
        else:
 
            # User isn't in that group
 
            return False
 

	
 
    def has_perm(self, users_group, perm):
 
        users_group = self.__get_users_group(users_group)
 
        perm = self._get_perm(perm)
 

	
 
        return UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == users_group)\
 
            .filter(UsersGroupToPerm.permission == perm).scalar() is not None
 
        return UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == users_group)\
 
            .filter(UserGroupToPerm.permission == perm).scalar() is not None
 

	
 
    def grant_perm(self, users_group, perm):
 
        users_group = self.__get_users_group(users_group)
 
        perm = self._get_perm(perm)
 

	
 
        # if this permission is already granted skip it
 
        _perm = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == users_group)\
 
            .filter(UsersGroupToPerm.permission == perm)\
 
        _perm = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == users_group)\
 
            .filter(UserGroupToPerm.permission == perm)\
 
            .scalar()
 
        if _perm:
 
            return
 

	
 
        new = UsersGroupToPerm()
 
        new = UserGroupToPerm()
 
        new.users_group = users_group
 
        new.permission = perm
 
        self.sa.add(new)
 

	
 
    def revoke_perm(self, users_group, perm):
 
        users_group = self.__get_users_group(users_group)
 
        perm = self._get_perm(perm)
 

	
 
        obj = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == users_group)\
 
            .filter(UsersGroupToPerm.permission == perm).scalar()
 
        obj = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == users_group)\
 
            .filter(UserGroupToPerm.permission == perm).scalar()
 
        if obj:
 
            self.sa.delete(obj)
rhodecode/model/validators.py
Show inline comments
 
@@ -7,25 +7,25 @@ import formencode
 
import logging
 
from collections import defaultdict
 
from pylons.i18n.translation import _
 
from webhelpers.pylonslib.secure_form import authentication_token
 

	
 
from formencode.validators import (
 
    UnicodeString, OneOf, Int, Number, Regex, Email, Bool, StringBoolean, Set,
 
    NotEmpty, IPAddress, CIDR
 
)
 
from rhodecode.lib.compat import OrderedSet
 
from rhodecode.lib import ipaddr
 
from rhodecode.lib.utils import repo_name_slug
 
from rhodecode.model.db import RepoGroup, Repository, UsersGroup, User,\
 
from rhodecode.model.db import RepoGroup, Repository, UserGroup, User,\
 
    ChangesetStatus
 
from rhodecode.lib.exceptions import LdapImportError
 
from rhodecode.config.routing import ADMIN_PREFIX
 
from rhodecode.lib.auth import HasReposGroupPermissionAny, HasPermissionAny
 

	
 
# silence warnings and pylint
 
UnicodeString, OneOf, Int, Number, Regex, Email, Bool, StringBoolean, Set, \
 
    NotEmpty, IPAddress, CIDR
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
@@ -120,58 +120,58 @@ def ValidRepoUser():
 
            try:
 
                User.query().filter(User.active == True)\
 
                    .filter(User.username == value).one()
 
            except Exception:
 
                msg = M(self, 'invalid_username', state, username=value)
 
                raise formencode.Invalid(msg, value, state,
 
                    error_dict=dict(username=msg)
 
                )
 

	
 
    return _validator
 

	
 

	
 
def ValidUsersGroup(edit=False, old_data={}):
 
def ValidUserGroup(edit=False, old_data={}):
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'invalid_group': _(u'Invalid users group name'),
 
            'group_exist': _(u'Users group "%(usersgroup)s" already exists'),
 
            'invalid_usersgroup_name':
 
                _(u'users group name may only contain  alphanumeric '
 
            'invalid_group': _(u'Invalid user group name'),
 
            'group_exist': _(u'User group "%(usergroup)s" already exists'),
 
            'invalid_usergroup_name':
 
                _(u'user group name may only contain alphanumeric '
 
                  'characters underscores, periods or dashes and must begin '
 
                  'with alphanumeric character')
 
        }
 

	
 
        def validate_python(self, value, state):
 
            if value in ['default']:
 
                msg = M(self, 'invalid_group', state)
 
                raise formencode.Invalid(msg, value, state,
 
                    error_dict=dict(users_group_name=msg)
 
                )
 
            #check if group is unique
 
            old_ugname = None
 
            if edit:
 
                old_id = old_data.get('users_group_id')
 
                old_ugname = UsersGroup.get(old_id).users_group_name
 
                old_ugname = UserGroup.get(old_id).users_group_name
 

	
 
            if old_ugname != value or not edit:
 
                is_existing_group = UsersGroup.get_by_group_name(value,
 
                is_existing_group = UserGroup.get_by_group_name(value,
 
                                                        case_insensitive=True)
 
                if is_existing_group:
 
                    msg = M(self, 'group_exist', state, usersgroup=value)
 
                    msg = M(self, 'group_exist', state, usergroup=value)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(users_group_name=msg)
 
                    )
 

	
 
            if re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value) is None:
 
                msg = M(self, 'invalid_usersgroup_name', state)
 
                msg = M(self, 'invalid_usergroup_name', state)
 
                raise formencode.Invalid(msg, value, state,
 
                    error_dict=dict(users_group_name=msg)
 
                )
 

	
 
    return _validator
 

	
 

	
 
def ValidReposGroup(edit=False, old_data={}):
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'group_parent_id': _(u'Cannot assign this group as parent'),
 
            'group_exists': _(u'Group "%(group_name)s" already exists'),
 
@@ -308,25 +308,25 @@ def ValidAuthToken():
 
    return _validator
 

	
 

	
 
def ValidRepoName(edit=False, old_data={}):
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'invalid_repo_name':
 
                _(u'Repository name %(repo)s is disallowed'),
 
            'repository_exists':
 
                _(u'Repository named %(repo)s already exists'),
 
            'repository_in_group_exists': _(u'Repository "%(repo)s" already '
 
                                            'exists in group "%(group)s"'),
 
            'same_group_exists': _(u'Repositories group with name "%(repo)s" '
 
            'same_group_exists': _(u'Repository group with name "%(repo)s" '
 
                                   'already exists')
 
        }
 

	
 
        def _to_python(self, value, state):
 
            repo_name = repo_name_slug(value.get('repo_name', ''))
 
            repo_group = value.get('repo_group')
 
            if repo_group:
 
                gr = RepoGroup.get(repo_group)
 
                group_path = gr.full_path
 
                group_name = gr.group_name
 
                # value needs to be aware of group name in order to check
 
                # db key This is an actual just the name to store in the
 
@@ -538,25 +538,25 @@ def CanCreateGroup(can_create_in_root=Fa
 
    return _validator
 

	
 

	
 
def ValidPerms(type_='repo'):
 
    if type_ == 'group':
 
        EMPTY_PERM = 'group.none'
 
    elif type_ == 'repo':
 
        EMPTY_PERM = 'repository.none'
 

	
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'perm_new_member_name':
 
                _(u'This username or users group name is not valid')
 
                _(u'This username or user group name is not valid')
 
        }
 

	
 
        def to_python(self, value, state):
 
            perms_update = OrderedSet()
 
            perms_new = OrderedSet()
 
            # build a list of permission to update and new permission to create
 

	
 
            #CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
 
            new_perms_group = defaultdict(dict)
 
            for k, v in value.copy().iteritems():
 
                if k.startswith('perm_new_member'):
 
                    del value[k]
 
@@ -595,27 +595,27 @@ def ValidPerms(type_='repo'):
 

	
 
            value['perms_updates'] = list(perms_update)
 
            value['perms_new'] = list(perms_new)
 

	
 
            # update permissions
 
            for k, v, t in perms_new:
 
                try:
 
                    if t is 'user':
 
                        self.user_db = User.query()\
 
                            .filter(User.active == True)\
 
                            .filter(User.username == k).one()
 
                    if t is 'users_group':
 
                        self.user_db = UsersGroup.query()\
 
                            .filter(UsersGroup.users_group_active == True)\
 
                            .filter(UsersGroup.users_group_name == k).one()
 
                        self.user_db = UserGroup.query()\
 
                            .filter(UserGroup.users_group_active == True)\
 
                            .filter(UserGroup.users_group_name == k).one()
 

	
 
                except Exception:
 
                    log.exception('Updated permission failed')
 
                    msg = M(self, 'perm_new_member_type', state)
 
                    raise formencode.Invalid(msg, value, state,
 
                        error_dict=dict(perm_new_member_name=msg)
 
                    )
 
            return value
 
    return _validator
 

	
 

	
 
def ValidSettings():
rhodecode/public/css/style.css
Show inline comments
 
@@ -151,74 +151,66 @@ div.options {
 

	
 
div.options a {
 
    height: 1%;
 
    display: block;
 
    text-decoration: none;
 
    margin: 0;
 
    padding: 3px 8px;
 
}
 

	
 
.top-left-rounded-corner {
 
    -webkit-border-top-left-radius: 8px;
 
    -khtml-border-radius-topleft: 8px;
 
    -moz-border-radius-topleft: 8px;
 
    border-top-left-radius: 8px;
 
}
 

	
 
.top-right-rounded-corner {
 
    -webkit-border-top-right-radius: 8px;
 
    -khtml-border-radius-topright: 8px;
 
    -moz-border-radius-topright: 8px;
 
    border-top-right-radius: 8px;
 
}
 

	
 
.bottom-left-rounded-corner {
 
    -webkit-border-bottom-left-radius: 8px;
 
    -khtml-border-radius-bottomleft: 8px;
 
    -moz-border-radius-bottomleft: 8px;
 
    border-bottom-left-radius: 8px;
 
}
 

	
 
.bottom-right-rounded-corner {
 
    -webkit-border-bottom-right-radius: 8px;
 
    -khtml-border-radius-bottomright: 8px;
 
    -moz-border-radius-bottomright: 8px;
 
    border-bottom-right-radius: 8px;
 
}
 

	
 
.top-left-rounded-corner-mid {
 
    -webkit-border-top-left-radius: 4px;
 
    -khtml-border-radius-topleft: 4px;
 
    -moz-border-radius-topleft: 4px;
 
    border-top-left-radius: 4px;
 
}
 

	
 
.top-right-rounded-corner-mid {
 
    -webkit-border-top-right-radius: 4px;
 
    -khtml-border-radius-topright: 4px;
 
    -moz-border-radius-topright: 4px;
 
    border-top-right-radius: 4px;
 
}
 

	
 
.bottom-left-rounded-corner-mid {
 
    -webkit-border-bottom-left-radius: 4px;
 
    -khtml-border-radius-bottomleft: 4px;
 
    -moz-border-radius-bottomleft: 4px;
 
    border-bottom-left-radius: 4px;
 
}
 

	
 
.bottom-right-rounded-corner-mid {
 
    -webkit-border-bottom-right-radius: 4px;
 
    -khtml-border-radius-bottomright: 4px;
 
    -moz-border-radius-bottomright: 4px;
 
    border-bottom-right-radius: 4px;
 
}
 

	
 
.help-block {
 
    color: #999999;
 
    display: block;
 
    margin-bottom: 0;
 
    margin-top: 5px;
 
}
 

	
 
.empty_data {
 
    color:#B9B9B9;
 
@@ -235,41 +227,39 @@ a.permalink:hover {
 
h1:hover > a.permalink,
 
h2:hover > a.permalink,
 
h3:hover > a.permalink,
 
h4:hover > a.permalink,
 
h5:hover > a.permalink,
 
h6:hover > a.permalink,
 
div:hover > a.permalink {
 
    visibility: visible;
 
}
 

	
 
#header {
 
}
 

	
 
#header ul#logged-user {
 
    margin-bottom: 5px !important;
 
    -webkit-border-radius: 0px 0px 8px 8px;
 
    -khtml-border-radius: 0px 0px 8px 8px;
 
    -moz-border-radius: 0px 0px 8px 8px;
 
    border-radius: 0px 0px 8px 8px;
 
    height: 37px;
 
    background-color: #003B76;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#003B76), to(#00376E) );
 
    background-image: -moz-linear-gradient(top, #003b76, #00376e);
 
    background-image: -ms-linear-gradient(top, #003b76, #00376e);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #003b76), color-stop(100%, #00376e) );
 
    background-image: -webkit-linear-gradient(top, #003b76, #00376e);
 
    background-image: -o-linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(to bottom, #003b76, #00376e);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#003b76',endColorstr='#00376e', GradientType=0 );
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
}
 

	
 
#header ul#logged-user li {
 
    list-style: none;
 
    float: left;
 
    margin: 8px 0 0;
 
    padding: 4px 12px;
 
    border-left: 1px solid #316293;
 
}
 

	
 
@@ -305,70 +295,67 @@ div:hover > a.permalink {
 
    color: #fff;
 
}
 

	
 
#header ul#logged-user li.highlight a:hover {
 
    color: #FFF;
 
}
 
#header-dd {
 
    clear: both;
 
    position: fixed !important;
 
    background-color: #003B76;
 
    opacity: 0.01;
 
    cursor: pointer;
 
    min-height: 10px;	
 
    min-height: 10px;
 
    width: 100% !important;
 
    -webkit-border-radius: 0px 0px 4px 4px;
 
    -khtml-border-radius: 0px 0px 4px 4px;
 
    -moz-border-radius: 0px 0px 4px 4px;
 
    border-radius: 0px 0px 4px 4px;
 
}
 

	
 
#header-dd:hover{
 
	opacity: 0.2;
 
    opacity: 0.2;
 
    -webkit-transition: opacity 0.5s ease-in-out;
 
    -moz-transition: opacity 0.5s ease-in-out;
 
    transition: opacity 0.5s ease-in-out;	
 
    transition: opacity 0.5s ease-in-out;
 
}
 

	
 
#header #header-inner {
 
    min-height: 44px;
 
    clear: both;
 
    position: relative;
 
    background-color: #003B76;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#003B76), to(#00376E) );
 
    background-image: -moz-linear-gradient(top, #003b76, #00376e);
 
    background-image: -ms-linear-gradient(top, #003b76, #00376e);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #003b76),color-stop(100%, #00376e) );
 
    background-image: -webkit-linear-gradient(top, #003b76, #00376e);
 
    background-image: -o-linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(to bottom, #003b76, #00376e);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#003b76',endColorstr='#00376e', GradientType=0 );
 
    margin: 0;
 
    padding: 0;
 
    display: block;
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
    -webkit-border-radius: 0px 0px 4px 4px;
 
    -khtml-border-radius: 0px 0px 4px 4px;
 
    -moz-border-radius: 0px 0px 4px 4px;
 
    border-radius: 0px 0px 4px 4px;
 
}
 
#header #header-inner.hover {
 
    width: 100% !important;
 
    -webkit-border-radius: 0px 0px 0px 0px;
 
    -khtml-border-radius: 0px 0px 0px 0px;
 
    -moz-border-radius: 0px 0px 0px 0px;
 
    border-radius: 0px 0px 0px 0px;
 
    position: fixed !important;
 
    z-index: 10000;    
 
    z-index: 10000;
 
}
 

	
 
.ie7 #header #header-inner.hover,
 
.ie8 #header #header-inner.hover,
 
.ie9 #header #header-inner.hover
 
{
 
    z-index: auto !important;
 
}
 

	
 
.header-pos-fix, .anchor {
 
    margin-top: -46px;
 
    padding-top: 46px;
 
@@ -430,25 +417,24 @@ div:hover > a.permalink {
 
    left: 0;
 
    height: 1%;
 
    display: block;
 
    clear: both;
 
    overflow: hidden;
 
    color: #FFF;
 
    font-weight: 700;
 
    text-decoration: none;
 
    background: #369;
 
    padding: 0;
 
    -webkit-border-radius: 4px 4px 4px 4px;
 
    -khtml-border-radius: 4px 4px 4px 4px;
 
    -moz-border-radius: 4px 4px 4px 4px;
 
    border-radius: 4px 4px 4px 4px;
 
}
 

	
 
#header #header-inner #quick li span.short {
 
    padding: 9px 6px 8px 6px;
 
}
 

	
 
#header #header-inner #quick li span {
 
    top: 0;
 
    right: 0;
 
    height: 1%;
 
    display: block;
 
@@ -1087,25 +1073,24 @@ tbody .yui-dt-editable { cursor: pointer
 
#content #right {
 
    margin: 0 60px 10px 290px;
 
}
 

	
 
#content div.box {
 
    clear: both;
 
/*    overflow: hidden;*/
 
    background: #fff;
 
    margin: 0 0 10px;
 
    padding: 0 0 10px;
 
    -webkit-border-radius: 4px 4px 4px 4px;
 
    -khtml-border-radius: 4px 4px 4px 4px;
 
    -moz-border-radius: 4px 4px 4px 4px;
 
    border-radius: 4px 4px 4px 4px;
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
}
 

	
 
#content div.box-left {
 
    width: 49%;
 
    clear: none;
 
    float: left;
 
    margin: 0 0 10px;
 
}
 

	
 
#content div.box-right {
 
@@ -1117,25 +1102,25 @@ tbody .yui-dt-editable { cursor: pointer
 

	
 
#content div.box div.title {
 
    clear: both;
 
    overflow: hidden;
 
    background-color: #003B76;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#003B76), to(#00376E) );
 
    background-image: -moz-linear-gradient(top, #003b76, #00376e);
 
    background-image: -ms-linear-gradient(top, #003b76, #00376e);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #003b76), color-stop(100%, #00376e) );
 
    background-image: -webkit-linear-gradient(top, #003b76, #00376e);
 
    background-image: -o-linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(to bottom, #003b76, #00376e);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#003b76', endColorstr='#00376e', GradientType=0 );
 
    margin: 0 0 20px;
 
    padding: 0;
 
}
 

	
 
#content div.box div.title h5 {
 
    float: left;
 
    border: none;
 
    color: #fff;
 
    text-transform: uppercase;
 
    margin: 0;
 
    padding: 11px 0 11px 10px;
 
@@ -1258,25 +1243,25 @@ tbody .yui-dt-editable { cursor: pointer
 
    width: 110%;
 
    height:14px;
 
    font-size:10px;
 
    text-align:center;
 
    cursor: pointer;
 
    color:#666;
 

	
 
    background:-webkit-gradient(linear,0% 50%,100% 50%,color-stop(0%,rgba(255,255,255,0)),color-stop(100%,rgba(64,96,128,0.1)));
 
    background:-webkit-linear-gradient(top,rgba(255,255,255,0),rgba(64,96,128,0.1));
 
    background:-moz-linear-gradient(top,rgba(255,255,255,0),rgba(64,96,128,0.1));
 
    background:-o-linear-gradient(top,rgba(255,255,255,0),rgba(64,96,128,0.1));
 
    background:-ms-linear-gradient(top,rgba(255,255,255,0),rgba(64,96,128,0.1));
 
    background:linear-gradient(top,rgba(255,255,255,0),rgba(64,96,128,0.1));
 
    background:linear-gradient(to bottom,rgba(255,255,255,0),rgba(64,96,128,0.1));
 

	
 
    display: none;
 
}
 
#content div.box div.expand .expandtext {
 
    background-color: #ffffff;
 
    padding: 2px;
 
    border-radius: 2px;
 
}
 

	
 
#content div.box div.message a {
 
    font-weight: 400 !important;
 
}
 
@@ -1614,25 +1599,24 @@ div.form div.fields div.field div.button
 
}
 
#content div.box table.noborder {
 
    border: 1px solid transparent;
 
}
 

	
 
#content div.box table {
 
    width: 100%;
 
    border-collapse: separate;
 
    margin: 0;
 
    padding: 0;
 
    border: 1px solid #eee;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
}
 

	
 
#content div.box table th {
 
    background: #eee;
 
    border-bottom: 1px solid #ddd;
 
    padding: 5px 0px 5px 5px;
 
    text-align: left;
 
}
 

	
 
#content div.box table th.left {
 
    text-align: left;
 
@@ -1940,25 +1924,24 @@ div.form div.fields div.field div.button
 
    margin-bottom: 9px;
 
}
 

	
 
#content div.box #summary p:first-of-type {
 
    margin-top: 9px;
 
}
 

	
 
.metatag {
 
    display: inline-block;
 
    margin-right: 1px;
 
    -webkit-border-radius: 4px 4px 4px 4px;
 
    -khtml-border-radius: 4px 4px 4px 4px;
 
    -moz-border-radius: 4px 4px 4px 4px;
 
    border-radius: 4px 4px 4px 4px;
 

	
 
    border: solid 1px #9CF;
 
    padding: 2px 3px 2px 3px !important;
 
    background-color: #DEF;
 
}
 

	
 
.metatag[tag="dead"] {
 
    background-color: #E44;
 
}
 

	
 
.metatag[tag="stale"] {
 
@@ -2018,30 +2001,29 @@ a.metatag[tag="license"]:hover {
 
    margin: -10px 0 0;
 
}
 

	
 
#footer div#footer-inner {
 
    background-color: #003B76;
 
    background-repeat : repeat-x;
 
    background-image : -khtml-gradient( linear, left top, left bottom, from(#003B76), to(#00376E));
 
    background-image : -moz-linear-gradient(top, #003b76, #00376e);
 
    background-image : -ms-linear-gradient( top, #003b76, #00376e);
 
    background-image : -webkit-gradient( linear, left top, left bottom, color-stop( 0%, #003b76), color-stop( 100%, #00376e));
 
    background-image : -webkit-linear-gradient( top, #003b76, #00376e));
 
    background-image : -o-linear-gradient( top, #003b76, #00376e));
 
    background-image : linear-gradient( top, #003b76, #00376e);
 
    background-image : linear-gradient(to bottom, #003b76, #00376e);
 
    filter :progid : DXImageTransform.Microsoft.gradient ( startColorstr = '#003b76', endColorstr = '#00376e', GradientType = 0);
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
    -webkit-border-radius: 4px 4px 4px 4px;
 
    -khtml-border-radius: 4px 4px 4px 4px;
 
    -moz-border-radius: 4px 4px 4px 4px;
 
    border-radius: 4px 4px 4px 4px;
 
}
 

	
 
#footer div#footer-inner p {
 
    padding: 15px 25px 15px 0;
 
    color: #FFF;
 
    font-weight: 700;
 
}
 

	
 
#footer div#footer-inner .footer-link {
 
    float: left;
 
    padding-left: 10px;
 
@@ -2054,25 +2036,25 @@ a.metatag[tag="license"]:hover {
 
#login div.title {
 
    clear: both;
 
    overflow: hidden;
 
    position: relative;
 
    background-color: #003B76;
 
    background-repeat : repeat-x;
 
    background-image : -khtml-gradient( linear, left top, left bottom, from(#003B76), to(#00376E));
 
    background-image : -moz-linear-gradient( top, #003b76, #00376e);
 
    background-image : -ms-linear-gradient( top, #003b76, #00376e);
 
    background-image : -webkit-gradient( linear, left top, left bottom, color-stop( 0%, #003b76), color-stop( 100%, #00376e));
 
    background-image : -webkit-linear-gradient( top, #003b76, #00376e));
 
    background-image : -o-linear-gradient( top, #003b76, #00376e));
 
    background-image : linear-gradient( top, #003b76, #00376e);
 
    background-image : linear-gradient(to bottom, #003b76, #00376e);
 
    filter : progid : DXImageTransform.Microsoft.gradient ( startColorstr = '#003b76', endColorstr = '#00376e', GradientType = 0);
 
    margin: 0 auto;
 
    padding: 0;
 
}
 

	
 
#login div.inner {
 
    background: #FFF url("../images/login.png") no-repeat top left;
 
    border-top: none;
 
    border-bottom: none;
 
    margin: 0 auto;
 
    padding: 20px;
 
}
 
@@ -2138,31 +2120,30 @@ a.metatag[tag="license"]:hover {
 
    padding: 4px;
 
    position: absolute;
 
    right: 0;
 
    width: 278px;
 
    background-color: #003B76;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#003B76), to(#00376E) );
 
    background-image: -moz-linear-gradient(top, #003b76, #00376e);
 
    background-image: -ms-linear-gradient(top, #003b76, #00376e);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #003b76), color-stop(100%, #00376e) );
 
    background-image: -webkit-linear-gradient(top, #003b76, #00376e);
 
    background-image: -o-linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(to bottom, #003b76, #00376e);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#003b76', endColorstr='#00376e', GradientType=0 );
 

	
 
    z-index: 999;
 
    -webkit-border-radius: 0px 0px 4px 4px;
 
    -khtml-border-radius: 0px 0px 4px 4px;
 
    -moz-border-radius: 0px 0px 4px 4px;
 
    border-radius: 0px 0px 4px 4px;
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
}
 
#quick_login h4 {
 
    color: #fff;
 
    padding: 5px 0px 5px 14px;
 
}
 

	
 
#quick_login .password_forgoten {
 
    padding-right: 10px;
 
    padding-top: 0px;
 
    text-align: left;
 
@@ -2204,25 +2185,25 @@ a.metatag[tag="license"]:hover {
 
#quick_login .big_gravatar {
 
    padding:4px 0px 0px 6px;
 
}
 
#quick_login .notifications {
 
    padding:4px 0px 0px 6px;
 
    color: #FFFFFF;
 
    font-weight: bold;
 
}
 
#quick_login .notifications a,
 
#quick_login .unread a {
 
    color: #FFFFFF;
 
    display: block;
 
    padding: 2px;    
 
    padding: 2px;
 
}
 
#quick_login .notifications a:hover,
 
#quick_login .unread a:hover {
 
    background-color: inherit !important;
 
}
 
#quick_login .email, #quick_login .unread {
 
    color: #FFFFFF;
 
    padding: 3px 3px 3px 6px;
 
}
 
#quick_login .links .logout {
 
}
 

	
 
@@ -2295,25 +2276,25 @@ a.metatag[tag="license"]:hover {
 
#register div.title {
 
    clear: both;
 
    overflow: hidden;
 
    position: relative;
 
    background-color: #003B76;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#003B76), to(#00376E) );
 
    background-image: -moz-linear-gradient(top, #003b76, #00376e);
 
    background-image: -ms-linear-gradient(top, #003b76, #00376e);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #003b76), color-stop(100%, #00376e) );
 
    background-image: -webkit-linear-gradient(top, #003b76, #00376e);
 
    background-image: -o-linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(top, #003b76, #00376e);
 
    background-image: linear-gradient(to bottom, #003b76, #00376e);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#003b76',
 
        endColorstr='#00376e', GradientType=0 );
 
    margin: 0 auto;
 
    padding: 0;
 
}
 

	
 
#register div.inner {
 
    background: #FFF;
 
    border-top: none;
 
    border-bottom: none;
 
    margin: 0 auto;
 
    padding: 20px;
 
@@ -2771,25 +2752,24 @@ h3.files_location {
 
    clear: both;
 
}
 

	
 
.right .changes .changed_total {
 
    display: block;
 
    float: right;
 
    text-align: center;
 
    min-width: 45px;
 
    cursor: pointer;
 
    color: #444444;
 
    background: #FEA;
 
    -webkit-border-radius: 0px 0px 0px 6px;
 
    -moz-border-radius: 0px 0px 0px 6px;
 
    border-radius: 0px 0px 0px 6px;
 
    padding: 1px;
 
}
 

	
 
.right .changes .added, .changed, .removed {
 
    display: block;
 
    padding: 1px;
 
    color: #444444;
 
    float: right;
 
    text-align: center;
 
    min-width: 15px;
 
}
 
@@ -2806,25 +2786,24 @@ h3.files_location {
 
    background: #FAA;
 
}
 

	
 
.right .merge {
 
    padding: 1px 3px 1px 3px;
 
    background-color: #fca062;
 
    font-size: 10px;
 
    font-weight: bold;
 
    color: #ffffff;
 
    text-transform: uppercase;
 
    white-space: nowrap;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
    margin-right: 2px;
 
}
 

	
 
.right .parent {
 
    color: #666666;
 
    clear:both;
 
}
 
.right .logtags {
 
    padding: 2px 2px 2px 2px;
 
}
 
.right .logtags .branchtag, .right .logtags .tagtag, .right .logtags .booktag {
 
@@ -2832,80 +2811,76 @@ h3.files_location {
 
}
 

	
 
.right .logtags .branchtag,
 
.logtags .branchtag,
 
.spantag {
 
    padding: 1px 3px 1px 3px;
 
    background-color: #bfbfbf;
 
    font-size: 10px;
 
    font-weight: bold;
 
    color: #ffffff;
 
    white-space: nowrap;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 
.right .logtags .branchtag a:hover, .logtags .branchtag a {
 
    color: #ffffff;
 
}
 
.right .logtags .branchtag a:hover, .logtags .branchtag a:hover {
 
    text-decoration: none;
 
    color: #ffffff;
 
}
 
.right .logtags .tagtag, .logtags .tagtag {
 
    padding: 1px 3px 1px 3px;
 
    background-color: #62cffc;
 
    font-size: 10px;
 
    font-weight: bold;
 
    color: #ffffff;
 
    white-space: nowrap;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 
.right .logtags .tagtag a:hover, .logtags .tagtag a {
 
    color: #ffffff;
 
}
 
.right .logtags .tagtag a:hover, .logtags .tagtag a:hover {
 
    text-decoration: none;
 
    color: #ffffff;
 
}
 
.right .logbooks .bookbook, .logbooks .bookbook, .right .logtags .bookbook, .logtags .bookbook {
 
    padding: 1px 3px 1px 3px;
 
    background-color: #46A546;
 
    font-size: 10px;
 
    font-weight: bold;
 
    color: #ffffff;
 
    text-transform: uppercase;
 
    white-space: nowrap;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 
.right .logbooks .bookbook, .logbooks .bookbook a, .right .logtags .bookbook, .logtags .bookbook a {
 
    color: #ffffff;
 
}
 
.right .logbooks .bookbook, .logbooks .bookbook a:hover, .right .logtags .bookbook, .logtags .bookbook a:hover {
 
    text-decoration: none;
 
    color: #ffffff;
 
}
 
div.browserblock {
 
    overflow: hidden;
 
    border: 1px solid #ccc;
 
    background: #f8f8f8;
 
    font-size: 100%;
 
    line-height: 125%;
 
    padding: 0;
 
    -webkit-border-radius: 6px 6px 0px 0px;
 
    -moz-border-radius: 6px 6px 0px 0px;
 
    border-radius: 6px 6px 0px 0px;
 
}
 

	
 
div.browserblock .browser-header {
 
    background: #FFF;
 
    padding: 10px 0px 15px 0px;
 
    width: 100%;
 
}
 

	
 
div.browserblock .browser-nav {
 
    float: left
 
}
 
@@ -3100,51 +3075,48 @@ table.code-browser .submodule-dir {
 
    visibility: hidden;
 
    position: absolute;
 
    z-index: 2;
 
}
 

	
 
#tip-box {
 
    position: absolute;
 

	
 
    background-color: #FFF;
 
    border: 2px solid #003367;
 
    font: 100% sans-serif;
 
    width: auto;
 
    opacity: 1px;
 
    opacity: 1;
 
    padding: 8px;
 

	
 
    white-space: pre-wrap;
 
    -webkit-border-radius: 8px 8px 8px 8px;
 
    -khtml-border-radius: 8px 8px 8px 8px;
 
    -moz-border-radius: 8px 8px 8px 8px;
 
    border-radius: 8px 8px 8px 8px;
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
    -moz-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
    -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
}
 

	
 
.hl-tip-box {
 
    visibility: hidden;
 
    position: absolute;
 
    color: #666;
 
    background-color: #FFF;
 
    border: 2px solid #003367;
 
    font: 100% sans-serif;
 
    width: auto;
 
    opacity: 1px;
 
    opacity: 1;
 
    padding: 8px;
 
    white-space: pre-wrap;
 
    -webkit-border-radius: 8px 8px 8px 8px;
 
    -khtml-border-radius: 8px 8px 8px 8px;
 
    -moz-border-radius: 8px 8px 8px 8px;
 
    border-radius: 8px 8px 8px 8px;
 
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6);
 
}
 

	
 

	
 
.mentions-container {
 
    width: 90% !important;
 
}
 
.mentions-container .yui-ac-content {
 
    width: 100% !important;
 
}
 

	
 
@@ -3173,25 +3145,24 @@ table.code-browser .submodule-dir {
 

	
 
.ac .yui-ac-content {
 
    position: absolute;
 
    border: 1px solid gray;
 
    background: #fff;
 
    z-index: 9050;
 
}
 

	
 
.ac .yui-ac-shadow {
 
    position: absolute;
 
    width: 100%;
 
    background: #000;
 
    -moz-opacity: 0.1px;
 
    opacity: .10;
 
    filter: alpha(opacity = 10);
 
    z-index: 9049;
 
    margin: .3em;
 
}
 

	
 
.ac .yui-ac-content ul {
 
    width: 100%;
 
    margin: 0;
 
    padding: 0;
 
    z-index: 9050;
 
}
 
@@ -3419,92 +3390,90 @@ table.code-browser .submodule-dir {
 
    color:red;
 
}
 

	
 
.error_msg {
 
    background-color: #c43c35;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#ee5f5b), to(#c43c35) );
 
    background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ee5f5b), color-stop(100%, #c43c35) );
 
    background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: -o-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: linear-gradient(to bottom, #ee5f5b, #c43c35);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ee5f5b',endColorstr='#c43c35', GradientType=0 );
 
    border-color: #c43c35 #c43c35 #882a25;
 
}
 

	
 
.warning_msg {
 
    color: #404040 !important;
 
    background-color: #eedc94;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#fceec1), to(#eedc94) );
 
    background-image: -moz-linear-gradient(top, #fceec1, #eedc94);
 
    background-image: -ms-linear-gradient(top, #fceec1, #eedc94);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fceec1), color-stop(100%, #eedc94) );
 
    background-image: -webkit-linear-gradient(top, #fceec1, #eedc94);
 
    background-image: -o-linear-gradient(top, #fceec1, #eedc94);
 
    background-image: linear-gradient(top, #fceec1, #eedc94);
 
    background-image: linear-gradient(to bottom, #fceec1, #eedc94);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fceec1', endColorstr='#eedc94', GradientType=0 );
 
    border-color: #eedc94 #eedc94 #e4c652;
 
}
 

	
 
.success_msg {
 
    background-color: #57a957;
 
    background-repeat: repeat-x !important;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#62c462), to(#57a957) );
 
    background-image: -moz-linear-gradient(top, #62c462, #57a957);
 
    background-image: -ms-linear-gradient(top, #62c462, #57a957);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #62c462), color-stop(100%, #57a957) );
 
    background-image: -webkit-linear-gradient(top, #62c462, #57a957);
 
    background-image: -o-linear-gradient(top, #62c462, #57a957);
 
    background-image: linear-gradient(top, #62c462, #57a957);
 
    background-image: linear-gradient(to bottom, #62c462, #57a957);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#62c462', endColorstr='#57a957', GradientType=0 );
 
    border-color: #57a957 #57a957 #3d773d;
 
}
 

	
 
.notice_msg {
 
    background-color: #339bb9;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#5bc0de), to(#339bb9) );
 
    background-image: -moz-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: -ms-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5bc0de), color-stop(100%, #339bb9) );
 
    background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: -o-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: linear-gradient(to bottom, #5bc0de, #339bb9);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5bc0de', endColorstr='#339bb9', GradientType=0 );
 
    border-color: #339bb9 #339bb9 #22697d;
 
}
 

	
 
.success_msg, .error_msg, .notice_msg, .warning_msg {
 
    font-size: 12px;
 
    font-weight: 700;
 
    min-height: 14px;
 
    line-height: 14px;
 
    margin-bottom: 10px;
 
    margin-top: 0;
 
    display: block;
 
    overflow: auto;
 
    padding: 6px 10px 6px 10px;
 
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 
    position: relative;
 
    color: #FFF;
 
    border-width: 1px;
 
    border-style: solid;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25);
 
    -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25);
 
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25);
 
}
 

	
 
#msg_close {
 
    background: transparent url("../icons/cross_grey_small.png") no-repeat scroll 0 0;
 
    cursor: pointer;
 
    height: 16px;
 
    position: absolute;
 
    right: 5px;
 
    top: 5px;
 
    width: 16px;
 
}
 
@@ -3515,51 +3484,49 @@ div#legend_container table {
 
    border: none !important;
 
}
 
div#legend_container table, div#legend_choices table {
 
    width: auto !important;
 
}
 

	
 
table#permissions_manage {
 
    width: 0 !important;
 
}
 

	
 
table#permissions_manage span.private_repo_msg {
 
    font-size: 0.8em;
 
    opacity: 0.6px;
 
    opacity: 0.6;
 
}
 

	
 
table#permissions_manage td.private_repo_msg {
 
    font-size: 0.8em;
 
}
 

	
 
table#permissions_manage tr#add_perm_input td {
 
    vertical-align: middle;
 
}
 

	
 
div.gravatar {
 
    background-color: #FFF;
 
    float: left;
 
    margin-right: 0.7em;
 
    padding: 1px 1px 1px 1px;
 
    line-height:0;
 
    -webkit-border-radius: 3px;
 
    -khtml-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 

	
 
div.gravatar img {
 
    -webkit-border-radius: 2px;
 
    -khtml-border-radius: 2px;
 
    -moz-border-radius: 2px;
 
    border-radius: 2px;
 
}
 

	
 
#header, #content, #footer {
 
    min-width: 978px;
 
}
 

	
 
#content {
 
    clear: both;
 
    /*overflow: hidden;*/
 
    padding: 10px 10px 14px 10px;
 
}
 
@@ -3577,129 +3544,127 @@ div.gravatar img {
 
}
 

	
 
.ui-btn {
 
    color: #515151;
 
    background-color: #DADADA;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#F4F4F4),to(#DADADA) );
 
    background-image: -moz-linear-gradient(top, #F4F4F4, #DADADA);
 
    background-image: -ms-linear-gradient(top, #F4F4F4, #DADADA);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #F4F4F4),color-stop(100%, #DADADA) );
 
    background-image: -webkit-linear-gradient(top, #F4F4F4, #DADADA) );
 
    background-image: -o-linear-gradient(top, #F4F4F4, #DADADA) );
 
    background-image: linear-gradient(top, #F4F4F4, #DADADA);
 
    background-image: linear-gradient(to bottom, #F4F4F4, #DADADA);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#F4F4F4', endColorstr='#DADADA', GradientType=0);
 

	
 
    border-top: 1px solid #DDD;
 
    border-left: 1px solid #c6c6c6;
 
    border-right: 1px solid #DDD;
 
    border-bottom: 1px solid #c6c6c6;
 
    color: #515151;
 
    outline: none;
 
    margin: 0px 3px 3px 0px;
 
    -webkit-border-radius: 4px 4px 4px 4px !important;
 
    -khtml-border-radius: 4px 4px 4px 4px !important;
 
    -moz-border-radius: 4px 4px 4px 4px !important;
 
    border-radius: 4px 4px 4px 4px !important;
 
    cursor: pointer !important;
 
    padding: 3px 3px 3px 3px;
 
    background-position: 0 -15px;
 

	
 
}
 

	
 
.ui-btn.disabled {
 
    color: #999;
 
}
 

	
 
.ui-btn.xsmall {
 
    padding: 1px 2px 1px 1px;
 
}
 

	
 
.ui-btn.large {
 
    padding: 6px 12px;
 
}
 

	
 
.ui-btn.clone {
 
    padding: 5px 2px 6px 1px;
 
    margin: 0px 0px 3px -4px;
 
    -webkit-border-radius: 0px 4px 4px 0px !important;
 
    -khtml-border-radius: 0px 4px 4px 0px !important;
 
    -moz-border-radius: 0px 4px 4px 0px !important;
 
    border-radius: 0px 4px 4px 0px !important;
 
    width: 100px;
 
    text-align: center;
 
    display: inline-block;
 
    position: relative;
 
    top: -2px;
 
}
 
.ui-btn:focus {
 
    outline: none;
 
}
 
.ui-btn:hover {
 
    background-position: 0 -15px;
 
    text-decoration: none;
 
    color: #515151;
 
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25), 0 0 3px #FFFFFF !important;
 
}
 

	
 
.ui-btn.disabled:hover {
 
    background-position:none;
 
    background-position: 0;
 
    color: #999;
 
    text-decoration: none;
 
    box-shadow: none !important;
 
}
 

	
 
.ui-btn.red {
 
    color:#fff;
 
    background-color: #c43c35;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#ee5f5b), to(#c43c35));
 
    background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ee5f5b), color-stop(100%, #c43c35));
 
    background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: -o-linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: linear-gradient(top, #ee5f5b, #c43c35);
 
    background-image: linear-gradient(to bottom, #ee5f5b, #c43c35);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ee5f5b', endColorstr='#c43c35', GradientType=0);
 
    border-color: #c43c35 #c43c35 #882a25;
 
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 
}
 

	
 

	
 
.ui-btn.blue {
 
    color:#fff;
 
    background-color: #339bb9;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#5bc0de), to(#339bb9));
 
    background-image: -moz-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: -ms-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5bc0de), color-stop(100%, #339bb9));
 
    background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: -o-linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: linear-gradient(top, #5bc0de, #339bb9);
 
    background-image: linear-gradient(to bottom, #5bc0de, #339bb9);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5bc0de', endColorstr='#339bb9', GradientType=0);
 
    border-color: #339bb9 #339bb9 #22697d;
 
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 
}
 

	
 
.ui-btn.green {
 
    background-color: #57a957;
 
    background-repeat: repeat-x;
 
    background-image: -khtml-gradient(linear, left top, left bottom, from(#62c462), to(#57a957));
 
    background-image: -moz-linear-gradient(top, #62c462, #57a957);
 
    background-image: -ms-linear-gradient(top, #62c462, #57a957);
 
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #62c462), color-stop(100%, #57a957));
 
    background-image: -webkit-linear-gradient(top, #62c462, #57a957);
 
    background-image: -o-linear-gradient(top, #62c462, #57a957);
 
    background-image: linear-gradient(top, #62c462, #57a957);
 
    background-image: linear-gradient(to bottom, #62c462, #57a957);
 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#62c462', endColorstr='#57a957', GradientType=0);
 
    border-color: #57a957 #57a957 #3d773d;
 
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
 
}
 

	
 
.ui-btn.blue.hidden {
 
    display: none;
 
}
 

	
 
.ui-btn.active {
 
    font-weight: bold;
 
}
 
@@ -3855,25 +3820,24 @@ div.form div.fields div.buttons input,
 
input.ui-button {
 
    background: #e5e3e3 url("../images/button.png") repeat-x;
 
    border-top: 1px solid #DDD;
 
    border-left: 1px solid #c6c6c6;
 
    border-right: 1px solid #DDD;
 
    border-bottom: 1px solid #c6c6c6;
 
    color: #515151 !important;
 
    outline: none;
 
    margin: 0;
 
    padding: 6px 12px;
 
    -webkit-border-radius: 4px 4px 4px 4px;
 
    -khtml-border-radius: 4px 4px 4px 4px;
 
    -moz-border-radius: 4px 4px 4px 4px;
 
    border-radius: 4px 4px 4px 4px;
 
    box-shadow: 0 1px 0 #ececec;
 
    cursor: pointer;
 
}
 

	
 
input.ui-button:hover {
 
    background: #b4b4b4 url("../images/button_selected.png") repeat-x;
 
    border-top: 1px solid #ccc;
 
    border-left: 1px solid #bebebe;
 
    border-right: 1px solid #b1b1b1;
 
    border-bottom: 1px solid #afafaf;
 
}
 
@@ -3987,24 +3951,28 @@ div.form div.fields div.field div.highli
 

	
 
#login div.form div.fields div.field div.label label, #register div.form div.fields div.field div.label label {
 
    color: #000;
 
    font-weight: 700;
 
}
 

	
 
#login div.form div.fields div.field div.input, #register div.form div.fields div.field div.input {
 
    float: left;
 
    margin: 0;
 
    padding: 0;
 
}
 

	
 
#login div.form div.fields div.field div.input input.large {
 
    width: 250px;
 
}
 

	
 
#login div.form div.fields div.field div.checkbox, #register div.form div.fields div.field div.checkbox {
 
    margin: 0 0 0 184px;
 
    padding: 0;
 
}
 

	
 
#login div.form div.fields div.field div.checkbox label, #register div.form div.fields div.field div.checkbox label {
 
    color: #565656;
 
    font-weight: 700;
 
}
 

	
 
#login div.form div.fields div.buttons input, #register div.form div.fields div.buttons input {
 
    color: #000;
 
@@ -4029,25 +3997,24 @@ div.form div.fields div.field div.highli
 
    padding-bottom: 5px;
 
}
 

	
 
div#legend_container table td, div#legend_choices table td {
 
    border: none !important;
 
    height: 20px !important;
 
    padding: 0 !important;
 
}
 

	
 
.q_filter_box {
 
    -webkit-box-shadow: rgba(0,0,0,0.07) 0 1px 2px inset;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
    border: 0 none;
 
    color: #AAAAAA;
 
    margin-bottom: -4px;
 
    margin-top: -4px;
 
    padding-left: 3px;
 
}
 

	
 
#node_filter {
 
    border: 0px solid #545454;
 
    color: #AAAAAA;
 
    padding-left: 3px;
 
@@ -4179,25 +4146,24 @@ div.readme .readme_box pre code {
 
}
 

	
 
div.readme .readme_box pre {
 
    margin: 1em 0;
 
    font-size: 12px;
 
    background-color: #eee;
 
    border: 1px solid #ddd;
 
    padding: 5px;
 
    color: #444;
 
    overflow: auto;
 
    -webkit-box-shadow: rgba(0,0,0,0.07) 0 1px 2px inset;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 

	
 
div.readme .readme_box table {
 
    display: table;
 
    border-collapse: separate;
 
    border-spacing: 2px;
 
    border-color: gray;
 
    width: auto !important;
 
}
 

	
 

	
 
@@ -4281,39 +4247,37 @@ div.rst-block  pre code {
 
}
 

	
 
div.rst-block  pre {
 
    margin: 1em 0;
 
    font-size: 12px;
 
    background-color: #eee;
 
    border: 1px solid #ddd;
 
    padding: 5px;
 
    color: #444;
 
    overflow: auto;
 
    -webkit-box-shadow: rgba(0,0,0,0.07) 0 1px 2px inset;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 

	
 

	
 
/** comment main **/
 
.comments {
 
    padding:10px 20px;
 
}
 

	
 
.comments .comment {
 
    border: 1px solid #ddd;
 
    margin-top: 10px;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
}
 

	
 
.comments .comment .meta {
 
    background: #f8f8f8;
 
    padding: 4px;
 
    border-bottom: 1px solid #ddd;
 
    height: 18px;
 
}
 

	
 
.comments .comment .meta img {
 
    vertical-align: middle;
 
@@ -4345,25 +4309,24 @@ div.rst-block  pre {
 
}
 

	
 
/** comment form **/
 

	
 
.status-block {
 
    min-height:80px;
 
    clear:both
 
}
 

	
 
.comment-form .clearfix {
 
    background: #EEE;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
    padding: 10px;
 
}
 

	
 
div.comment-form {
 
    margin-top: 20px;
 
}
 

	
 
.comment-form strong {
 
    display: block;
 
    margin-bottom: 15px;
 
}
 
@@ -4431,25 +4394,24 @@ form.comment-form {
 
    text-align: center;
 
    vertical-align: top;
 

	
 
}
 
.comment-inline-form .overlay.submitting .overlay-text {
 
    width:100%;
 
    margin-top:5%;
 
}
 

	
 
.comment-inline-form .clearfix {
 
    background: #EEE;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
    padding: 5px;
 
}
 

	
 
div.comment-inline-form {
 
    padding:4px 0px 6px 0px;
 
}
 

	
 

	
 
tr.hl-comment {
 
/*
 
    background-color: #FFFFCC !important;
 
@@ -4508,25 +4470,24 @@ form.comment-inline-form {
 
    padding:10px 20px;
 
}
 

	
 
.inline-comments div.rst-block  {
 
    clear:both;
 
    overflow:hidden;
 
    margin:0;
 
    padding:0 20px 0px;
 
}
 
.inline-comments .comment {
 
    border: 1px solid #ddd;
 
    -webkit-border-radius: 4px;
 
    -moz-border-radius: 4px;
 
    border-radius: 4px;
 
    margin: 3px 3px 5px 5px;
 
    background-color: #FAFAFA;
 
}
 
.inline-comments .add-comment {
 
    padding: 2px 4px 8px 5px;
 
}
 

	
 
.inline-comments .comment-wrapp {
 
    padding:1px;
 
}
 
.inline-comments .comment .meta {
 
@@ -4575,50 +4536,48 @@ form.comment-inline-form {
 
    padding: 10px 8px 8px 8px !important;
 
}
 

	
 
.menu_link_notifications {
 
    padding: 4px 4px !important;
 
    margin: 7px 4px 0px 0px !important;
 
    text-align: center;
 
    color:#888 !important;
 
    font-size: 10px;
 
    background-color: #DEDEDE !important;
 
    border-radius: 4px !important;
 
    -webkit-border-radius: 4px !important;
 
    -moz-border-radius: 4px !important;
 
}
 

	
 
.notification-header {
 
    padding-top:6px;
 
}
 
.notification-header .desc {
 
    font-size: 16px;
 
    height: 24px;
 
    float: left
 
}
 
.notification-list .container.unread {
 
    background: none repeat scroll 0 0 rgba(255, 255, 180, 0.6);
 
}
 
.notification-header .gravatar {
 
    background: none repeat scroll 0 0 transparent;
 
    padding: 0px 0px 0px 8px;
 
}
 
.notification-list .container .notification-header .desc {
 
    font-weight: bold;
 
    font-size: 17px;
 
}
 
.notification-table {
 
    border: 1px solid #ccc;
 
    -webkit-border-radius: 6px 6px 6px 6px;
 
    -moz-border-radius: 6px 6px 6px 6px;
 
    border-radius: 6px 6px 6px 6px;
 
    clear: both;
 
    margin: 0px 20px 0px 20px;
 
}
 
.notification-header .delete-notifications {
 
    float: right;
 
    padding-top: 8px;
 
    cursor: pointer;
 
}
 
.notification-header .read-notifications {
 
    float: right;
 
    padding-top: 8px;
 
@@ -4651,25 +4610,24 @@ PULL REQUESTS
 
    padding:10px 10px 10px 0px;
 
    font-size:16px;
 
    font-weight: bold;
 
}
 

	
 
#perms .perm_tag {
 
    padding: 1px 3px 1px 3px;
 
    font-size: 10px;
 
    font-weight: bold;
 
    text-transform: uppercase;
 
    white-space: nowrap;
 
    -webkit-border-radius: 3px;
 
    -moz-border-radius: 3px;
 
    border-radius: 3px;
 
}
 

	
 
#perms .perm_tag.admin {
 
    background-color: #B94A48;
 
    color: #ffffff;
 
}
 

	
 
#perms .perm_tag.write {
 
    background-color: #DB7525;
 
    color: #ffffff;
 
}
 
@@ -4689,36 +4647,53 @@ PULL REQUESTS
 
    padding:2px;
 
}
 
.perm-gravatar-ac {
 
    vertical-align:middle;
 
    padding:2px;
 
    width: 14px;
 
    height: 14px;
 
}
 

	
 
/*****************************************************************************
 
                                  DIFFS CSS
 
******************************************************************************/
 
.diff-collapse{
 
    text-align: center;
 
    margin-bottom: -15px;
 
}
 
.diff-collapse-button{
 
    cursor: pointer;
 
    color: #666;
 
    font-size: 16px;
 
}
 
.diff-container {
 

	
 
}
 

	
 
.diff-container.hidden{
 
    display: none;
 
    overflow: hidden;
 
}
 

	
 

	
 
div.diffblock {
 
    overflow: auto;
 
    padding: 0px;
 
    border: 1px solid #ccc;
 
    background: #f8f8f8;
 
    font-size: 100%;
 
    line-height: 100%;
 
    /* new */
 
    line-height: 125%;
 
    -webkit-border-radius: 6px 6px 0px 0px;
 
    -moz-border-radius: 6px 6px 0px 0px;
 
    border-radius: 6px 6px 0px 0px;
 
}
 
div.diffblock.margined {
 
    margin: 0px 20px 0px 20px;
 
}
 
div.diffblock .code-header {
 
    border-bottom: 1px solid #CCCCCC;
 
    background: #EEEEEE;
 
    padding:10px 0 10px 0;
 
    height: 14px;
 
}
 

	
 
@@ -4778,30 +4753,31 @@ div.diffblock .children {
 
}
 

	
 
div.diffblock .code-body {
 
    background: #FFFFFF;
 
}
 
div.diffblock pre.raw {
 
    background: #FFFFFF;
 
    color:#000000;
 
}
 
table.code-difftable {
 
    border-collapse: collapse;
 
    width: 99%;
 
    border-radius: 0px !important;
 
}
 
table.code-difftable td {
 
    padding: 0 !important;
 
    background: none !important;
 
    border:0 !important;
 
    vertical-align: none !important;
 
    vertical-align: baseline !important
 
}
 
table.code-difftable .context {
 
    background:none repeat scroll 0 0 #DDE7EF;
 
}
 
table.code-difftable .add {
 
    background:none repeat scroll 0 0 #DDFFDD;
 
}
 
table.code-difftable .add ins {
 
    background:none repeat scroll 0 0 #AAFFAA;
 
    text-decoration:none;
 
}
 
table.code-difftable .del {
 
@@ -4878,12 +4854,17 @@ table.code-difftable .code pre {
 
    background-position: right !important;
 
    background-position: 0% 50% !important;
 
}
 
.diffblock.margined.comm .line .code.no-comment:hover {
 
    background-image: none !important;
 
    cursor: auto !important;
 
    background-color: inherit !important;
 
}
 

	
 
div.comment:target>.comment-wrapp {
 
    border: solid 2px #ee0 !important;
 
}
 

	
 
.lineno:target a {
 
    border: solid 2px #ee0 !important;
 
    margin: -2px;
 
}
rhodecode/public/js/rhodecode.js
Show inline comments
 
@@ -293,30 +293,43 @@ var pyroutes = (function() {
 
    var vsprintf = function(fmt, argv) {
 
        argv.unshift(fmt);
 
        return sprintf.apply(null, argv);
 
    };
 
    return {
 
        'url': function(route_name, params) {
 
            var result = route_name;
 
            if (typeof(params) != 'object'){
 
            	params = {};
 
            }
 
            if (matchlist.hasOwnProperty(route_name)) {
 
                var route = matchlist[route_name];
 
                // param substitution
 
                for(var i=0; i < route[1].length; i++) {
 

	
 
                   if (!params.hasOwnProperty(route[1][i]))
 
                        throw new Error(route[1][i] + ' missing in "' + route_name + '" route generation');
 
                }
 
                result = sprintf(route[0], params);
 
                
 
                var ret = [];
 
                //extra params => GET
 
                for(param in params){
 
                	if (route[1].indexOf(param) == -1){
 
                		ret.push(encodeURIComponent(param) + "=" + encodeURIComponent(params[param]));	
 
                	}
 
                }
 
                var _parts = ret.join("&");
 
                if(_parts){
 
                	result = result +'?'+ _parts
 
                }
 
            }
 

	
 
            return result;
 
        },
 
    	'register': function(route_name, route_tmpl, req_params) {
 
    		if (typeof(req_params) != 'object') {
 
    			req_params = [];
 
    		}
 
    		//fix escape
 
    		route_tmpl = unescape(route_tmpl);
 
    		keys = [];
 
    		for (o in req_params){
 
@@ -1280,25 +1293,25 @@ var MembersAutoComplete = function (divi
 
            // Match against each name of each contact
 
            for (; i < l; i++) {
 
                contact = myUsers[i];
 
                if (((contact.fname+"").toLowerCase().indexOf(query) > -1) || 
 
                   	 ((contact.lname+"").toLowerCase().indexOf(query) > -1) || 
 
                   	 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
 
                       matches[matches.length] = contact;
 
                   }
 
            }
 
            return matches;
 
        };
 

	
 
    // Define a custom search function for the DataSource of usersGroups
 
    // Define a custom search function for the DataSource of userGroups
 
    var matchGroups = function (sQuery) {
 
            // Case insensitive matching
 
            var query = sQuery.toLowerCase();
 
            var i = 0;
 
            var l = myGroups.length;
 
            var matches = [];
 

	
 
            // Match against each name of each contact
 
            for (; i < l; i++) {
 
                matched_group = myGroups[i];
 
                if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
 
                    matches[matches.length] = matched_group;
 
@@ -1698,25 +1711,25 @@ var PullRequestAutoComplete = function (
 
            // Match against each name of each contact
 
            for (; i < l; i++) {
 
                contact = myUsers[i];
 
                if (((contact.fname+"").toLowerCase().indexOf(query) > -1) || 
 
                   	 ((contact.lname+"").toLowerCase().indexOf(query) > -1) || 
 
                   	 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
 
                       matches[matches.length] = contact;
 
                   }
 
            }
 
            return matches;
 
        };
 

	
 
    // Define a custom search function for the DataSource of usersGroups
 
    // Define a custom search function for the DataSource of userGroups
 
    var matchGroups = function (sQuery) {
 
            // Case insensitive matching
 
            var query = sQuery.toLowerCase();
 
            var i = 0;
 
            var l = myGroups.length;
 
            var matches = [];
 

	
 
            // Match against each name of each contact
 
            for (; i < l; i++) {
 
                matched_group = myGroups[i];
 
                if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
 
                    matches[matches.length] = matched_group;
 
@@ -2140,12 +2153,35 @@ var MultiSelectWidget = function(selecte
 
	YUE.addListener(['add_element','remove_element',
 
	               'add_all_elements','remove_all_elements'],'click',
 
	               prompts_action_callback)
 
	if (form_id !== undefined) {
 
		YUE.addListener(form_id,'submit',function(){
 
		    var choosen = YUD.get(selected_container);
 
		    for (var i = 0; i < choosen.options.length; i++) {
 
		        choosen.options[i].selected = 'selected';
 
		    }
 
		});
 
	}
 
}
 

	
 

	
 
// global hooks after DOM is loaded
 

	
 
YUE.onDOMReady(function(){
 
	YUE.on(YUQ('.diff-collapse-button'), 'click', function(e){
 
		var button = e.currentTarget;
 
		var t = YUD.get(button).getAttribute('target');
 
	    console.log(t);
 
		if(YUD.hasClass(t, 'hidden')){
 
			YUD.removeClass(t, 'hidden');
 
			YUD.get(button).innerHTML = "&uarr; {0} &uarr;".format(_TM['collapse diff']);
 
		}
 
		else if(!YUD.hasClass(t, 'hidden')){
 
			YUD.addClass(t, 'hidden');
 
			YUD.get(button).innerHTML = "&darr; {0} &darr;".format(_TM['expand diff']);
 
		}
 
	});
 
	
 
	
 
	
 
});
 

	
rhodecode/templates/admin/notifications/show_notification.html
Show inline comments
 
@@ -30,25 +30,30 @@
 
      <div id="notification_${c.notification.notification_id}">
 
        <div class="notification-header">
 
          <div class="gravatar">
 
              <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(c.notification.created_by_user.email),24)}"/>
 
          </div>
 
          <div class="desc">
 
              ${c.notification.description}
 
          </div>
 
          <div class="delete-notifications">
 
            <span id="${c.notification.notification_id}" class="delete-notification delete_icon action"></span>
 
          </div>
 
        </div>
 
        <div class="notification-body">${h.rst_w_mentions(c.notification.body)}</div>
 
        <div class="notification-body">
 
        <div class="notification-subject">${h.literal(c.notification.subject)}</div>
 
        %if c.notification.body:
 
            ${h.rst_w_mentions(c.notification.body)}
 
        %endif
 
        </div>
 
      </div>
 
    </div>
 
</div>
 
<script type="text/javascript">
 
var url = "${url('notification', notification_id='__NOTIFICATION_ID__')}";
 
var main = "${url('notifications')}";
 
   YUE.on(YUQ('.delete-notification'),'click',function(e){
 
       var notification_id = e.currentTarget.id;
 
       deleteNotification(url,notification_id,[function(){window.location=main}])
 
   })
 
</script>
 
</%def>
rhodecode/templates/admin/permissions/permissions.html
Show inline comments
 
@@ -50,25 +50,25 @@
 
                    ${_('overwrite existing settings')}</span> </label>
 
                </div>
 
            </div>
 
            <div class="field">
 
                <div class="label">
 
                    <label for="default_group_perm">${_('Repository group')}:</label>
 
                </div>
 
                <div class="select">
 
                    ${h.select('default_group_perm','',c.group_perms_choices)}
 
                    ${h.checkbox('overwrite_default_group','true')}
 
                    <label for="overwrite_default_group">
 
                    <span class="tooltip"
 
                    title="${h.tooltip(_('All default permissions on each repository group will be reset to choosen permission, note that all custom default permission on repositories group will be lost'))}">
 
                    title="${h.tooltip(_('All default permissions on each repository group will be reset to choosen permission, note that all custom default permission on repository groups will be lost'))}">
 
                    ${_('overwrite existing settings')}</span> </label>
 

	
 
                </div>
 
            </div>
 
            <div class="field">
 
                <div class="label">
 
                    <label for="default_register">${_('Registration')}:</label>
 
                </div>
 
                <div class="select">
 
                    ${h.select('default_register','',c.register_choices)}
 
                </div>
 
            </div>
rhodecode/templates/admin/repos/repo_edit_perms.html
Show inline comments
 
@@ -29,41 +29,41 @@
 
            </td>
 
            <td>
 
              %if r2p.user.username !='default':
 
                <span class="delete_icon action_button" onclick="ajaxActionUser(${r2p.user.user_id},'${'id%s'%id(r2p.user.username)}')">
 
                ${_('revoke')}
 
                </span>
 
              %endif
 
            </td>
 
        </tr>
 
        %endif
 
    %endfor
 

	
 
    ## USERS GROUPS
 
    ## USER GROUPS
 
    %for g2p in c.repo_info.users_group_to_perm:
 
        <tr id="id${id(g2p.users_group.users_group_name)}">
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'repository.none')}</td>
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'repository.read')}</td>
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'repository.write')}</td>
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'repository.admin')}</td>
 
            <td style="white-space: nowrap;">
 
                <img class="perm-gravatar" src="${h.url('/images/icons/group.png')}"/>
 
                %if h.HasPermissionAny('hg.admin')():
 
                 <a href="${h.url('edit_users_group',id=g2p.users_group.users_group_id)}">${g2p.users_group.users_group_name}</a>
 
                %else:
 
                 ${g2p.users_group.users_group_name}
 
                %endif
 
            </td>
 
            <td>
 
                <span class="delete_icon action_button" onclick="ajaxActionUsersGroup(${g2p.users_group.users_group_id},'${'id%s'%id(g2p.users_group.users_group_name)}')">
 
                <span class="delete_icon action_button" onclick="ajaxActionUserGroup(${g2p.users_group.users_group_id},'${'id%s'%id(g2p.users_group.users_group_name)}')">
 
                ${_('revoke')}
 
                </span>
 
            </td>
 
        </tr>
 
    %endfor
 
    <%
 
    _tmpl = h.literal("""' \
 
        <td><input type="radio" value="repository.none" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td><input type="radio" value="repository.read" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td><input type="radio" value="repository.write" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td><input type="radio" value="repository.admin" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td class="ac"> \
 
@@ -92,33 +92,33 @@ function ajaxActionUser(user_id, field_i
 
        success: function (o) {
 
            var tr = YUD.get(String(field_id));
 
            tr.parentNode.removeChild(tr);
 
        },
 
        failure: function (o) {
 
            alert("${_('Failed to remove user')}");
 
        },
 
    };
 
    var postData = '_method=delete&user_id=' + user_id;
 
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
 
};
 

	
 
function ajaxActionUsersGroup(users_group_id,field_id){
 
function ajaxActionUserGroup(users_group_id,field_id){
 
    var sUrl = "${h.url('delete_repo_users_group',repo_name=c.repo_name)}";
 
    var callback = {
 
        success:function(o){
 
            var tr = YUD.get(String(field_id));
 
            tr.parentNode.removeChild(tr);
 
        },
 
        failure:function(o){
 
            alert("${_('Failed to remove users group')}");
 
            alert("${_('Failed to remove user group')}");
 
        },
 
    };
 
    var postData = '_method=delete&users_group_id='+users_group_id;
 
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
 
};
 

	
 
YUE.onDOMReady(function () {
 
    if (!YUD.hasClass('perm_new_member_name', 'error')) {
 
        YUD.setStyle('add_perm_input', 'display', 'none');
 
    }
 
    YAHOO.util.Event.addListener('add_perm', 'click', function () {
 
        addPermAction(${_tmpl}, ${c.users_array|n}, ${c.users_groups_array|n});
rhodecode/templates/admin/repos_groups/repos_group_edit_perms.html
Show inline comments
 
@@ -31,36 +31,36 @@
 
            <td>${h.radio('u_perm_%s' % r2p.user.username,'group.read', disabled="disabled")}</td>
 
            <td>${h.radio('u_perm_%s' % r2p.user.username,'group.write', disabled="disabled")}</td>
 
            <td>${h.radio('u_perm_%s' % r2p.user.username,'group.admin', disabled="disabled")}</td>
 
            <td style="white-space: nowrap;">
 
                <img class="perm-gravatar" src="${h.gravatar_url(r2p.user.email,14)}"/>${r2p.user.username if r2p.user.username != 'default' else _('default')}
 
            </td>
 
            <td>
 
            </td>
 
            %endif
 
        </tr>
 
    %endfor
 

	
 
    ## USERS GROUPS
 
    ## USER GROUPS
 
    %for g2p in c.repos_group.users_group_to_perm:
 
        <tr id="id${id(g2p.users_group.users_group_name)}">
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'group.none')}</td>
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'group.read')}</td>
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'group.write')}</td>
 
            <td>${h.radio('g_perm_%s' % g2p.users_group.users_group_name,'group.admin')}</td>
 
            <td style="white-space: nowrap;">
 
                <img class="perm-gravatar" src="${h.url('/images/icons/group.png')}"/>${g2p.users_group.users_group_name}
 
            </td>
 
            <td>
 
                <span class="delete_icon action_button" onclick="ajaxActionUsersGroup(${g2p.users_group.users_group_id},'${'id%s'%id(g2p.users_group.users_group_name)}')">
 
                <span class="delete_icon action_button" onclick="ajaxActionUserGroup(${g2p.users_group.users_group_id},'${'id%s'%id(g2p.users_group.users_group_name)}')">
 
                ${_('revoke')}
 
                </span>
 
            </td>
 
        </tr>
 
    %endfor
 
<%
 
    _tmpl = h.literal("""' \
 
        <td><input type="radio" value="group.none" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td><input type="radio" value="group.read" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td><input type="radio" value="group.write" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td><input type="radio" value="group.admin" name="perm_new_member_{0}" id="perm_new_member_{0}"></td> \
 
        <td class="ac"> \
 
@@ -96,33 +96,33 @@ function ajaxActionUser(user_id, field_i
 
            var tr = YUD.get(String(field_id));
 
            tr.parentNode.removeChild(tr);
 
        },
 
        failure: function (o) {
 
            alert("${_('Failed to remove user')}");
 
        },
 
    };
 
    var recursive = YUD.get('recursive').checked;
 
    var postData = '_method=delete&recursive={0}&user_id={1}'.format(recursive,user_id);
 
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
 
};
 

	
 
function ajaxActionUsersGroup(users_group_id,field_id){
 
function ajaxActionUserGroup(users_group_id,field_id){
 
    var sUrl = "${h.url('delete_repos_group_users_group_perm',group_name=c.repos_group.group_name)}";
 
    var callback = {
 
        success:function(o){
 
            var tr = YUD.get(String(field_id));
 
            tr.parentNode.removeChild(tr);
 
        },
 
        failure:function(o){
 
            alert("${_('Failed to remove users group')}");
 
            alert("${_('Failed to remove user group')}");
 
        },
 
    };
 
    var recursive = YUD.get('recursive').checked;
 
    var postData = '_method=delete&recursive={0}&users_group_id={1}'.format(recursive,users_group_id);
 
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
 
};
 

	
 
YUE.onDOMReady(function () {
 
    if (!YUD.hasClass('perm_new_member_name', 'error')) {
 
        YUD.setStyle('add_perm_input', 'display', 'none');
 
    }
 
    YAHOO.util.Event.addListener('add_perm', 'click', function () {
rhodecode/templates/admin/repos_groups/repos_groups_show.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Repositories groups administration')} - ${c.rhodecode_name}
 
    ${_('Repository groups administration')} - ${c.rhodecode_name}
 
</%def>
 

	
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${_('repositories groups')}
 
    ${_('repository groups')}
 
</%def>
 
<%def name="page_nav()">
 
    ${self.menu('admin')}
 
</%def>
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
        <ul class="links">
 
          <li>
 
            %if h.HasPermissionAny('hg.admin')():
 
@@ -39,40 +39,40 @@
 
                        <th class="left"><a href="#">${_('Number of toplevel repositories')}</a></th>
 
                        <th class="left" colspan="2">${_('action')}</th>
 
                    </tr>
 
                </thead>
 

	
 
                ## REPO GROUPS
 

	
 
                % for gr in c.groups:
 
                    <% gr_cn = gr.repositories.count() %>
 
                  <tr>
 
                      <td>
 
                          <div style="white-space: nowrap">
 
                          <img class="icon" alt="${_('Repositories group')}" src="${h.url('/images/icons/database_link.png')}"/>
 
                          <img class="icon" alt="${_('Repository group')}" src="${h.url('/images/icons/database_link.png')}"/>
 
                          ${h.link_to(h.literal(' &raquo; '.join(map(h.safe_unicode,[g.name for g in gr.parents+[gr]]))), url('repos_group_home',group_name=gr.group_name))}
 
                          </div>
 
                      </td>
 
                      <td>${gr.group_description}</td>
 
                      <td><b>${gr_cn}</b></td>
 
                      <td>
 
                       <a href="${h.url('edit_repos_group',group_name=gr.group_name)}" title="${_('edit')}">
 
                         ${h.submit('edit_%s' % gr.group_name,_('edit'),class_="edit_icon action_button")}
 
                       </a>
 
                      </td>
 
                      <td>
 
                       ${h.form(url('repos_group', group_name=gr.group_name),method='delete')}
 
                         ${h.submit('remove_%s' % gr.name,_('delete'),class_="delete_icon action_button",onclick="return confirm('"+ungettext('Confirm to delete this group: %s with %s repository','Confirm to delete this group: %s with %s repositories',gr_cn) % (gr.name,gr_cn)+"');")}
 
                       ${h.end_form()}
 
                      </td>
 
                  </tr>
 
                % endfor
 

	
 
            </table>
 
            % else:
 
                ${_('There are no repositories groups yet')}
 
                ${_('There are no repository groups yet')}
 
            % endif
 

	
 
    </div>
 
</div>
 

	
 
</%def>
rhodecode/templates/admin/settings/settings.html
Show inline comments
 
@@ -55,64 +55,64 @@
 
    ${h.form(url('admin_setting', setting_id='whoosh'),method='put')}
 
    <div class="form">
 
        <!-- fields -->
 

	
 
        <div class="fields">
 
            <div class="field">
 
                <div class="label label-checkbox">
 
                    <label>${_('index build option')}:</label>
 
                </div>
 
                <div class="checkboxes">
 
                    <div class="checkbox">
 
                        ${h.checkbox('full_index',True)}
 
                        <label for="full_index">${_('build from scratch')}</label>
 
                        <label for="full_index">${_('Build from scratch')}</label>
 
                    </div>
 
                </div>
 
            </div>
 

	
 
            <div class="buttons">
 
            ${h.submit('reindex',_('Reindex'),class_="ui-btn large")}
 
            </div>
 
        </div>
 
    </div>
 
    ${h.end_form()}
 

	
 
    <h3>${_('Global application settings')}</h3>
 
    ${h.form(url('admin_setting', setting_id='global'),method='put')}
 
    <div class="form">
 
        <!-- fields -->
 

	
 
        <div class="fields">
 

	
 
             <div class="field">
 
                <div class="label">
 
                    <label for="rhodecode_title">${_('Application name')}:</label>
 
                    <label for="rhodecode_title">${_('Site branding')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('rhodecode_title',size=30)}
 
                </div>
 
             </div>
 

	
 
            <div class="field">
 
                <div class="label">
 
                    <label for="rhodecode_realm">${_('Realm text')}:</label>
 
                    <label for="rhodecode_realm">${_('HTTP authentication realm')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('rhodecode_realm',size=30)}
 
                </div>
 
            </div>
 

	
 
            <div class="field">
 
                <div class="label">
 
                    <label for="rhodecode_ga_code">${_('GA code')}:</label>
 
                    <label for="rhodecode_ga_code">${_('Google Analytics code')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('rhodecode_ga_code',size=30)}
 
                </div>
 
            </div>
 

	
 
            <div class="buttons">
 
                ${h.submit('save',_('Save settings'),class_="ui-btn large")}
 
                ${h.reset('reset',_('Reset'),class_="ui-btn large")}
 
           </div>
 
        </div>
 
    </div>
rhodecode/templates/admin/users/user_edit.html
Show inline comments
 
@@ -31,30 +31,30 @@
 
               <div class="gravatar"><img alt="gravatar" src="${h.gravatar_url(c.user.email)}"/></div>
 
                <p>
 
                %if c.use_gravatar:
 
                <strong>${_('Change your avatar at')} <a href="http://gravatar.com">gravatar.com</a></strong>
 
                <br/>${_('Using')} ${c.user.email}
 
                %else:
 
                <br/>${c.user.email}
 
                %endif
 
           </div>
 
        </div>
 
        <div class="field">
 
            <div class="label">
 
                <label>${_('API key')}</label> ${c.user.api_key}
 
                <label>${_('API key')}:</label> ${c.user.api_key}
 
            </div>
 
        </div>
 
        <div class="field">
 
            <div class="label">
 
                <label>${_('Your IP')}</label> ${c.perm_user.ip_addr or "?"}
 
                <label>${_('Current IP')}:</label> ${c.perm_user.ip_addr or "?"}
 
            </div>
 
        </div>
 
        <div class="fields">
 
             <div class="field">
 
                <div class="label">
 
                    <label for="username">${_('Username')}:</label>
 
                </div>
 
                <div class="input">
 
                    %if c.ldap_dn:
 
                        ${h.text('username',class_='medium disabled', readonly="readonly")}
 
                    %else:
 
                        ${h.text('username',class_='medium')}
rhodecode/templates/admin/users/user_edit_my_account.html
Show inline comments
 
@@ -93,24 +93,25 @@
 
    </div>
 
    <div id="my_container" style="display:none">
 
        <div class="table yui-skin-sam" id="repos_list_wrap"></div>
 
        <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
 
    </div>
 
    <div id="pullrequests_container" class="table" style="display:none">
 
        ## loaded via AJAX
 
        ${_('Loading...')}
 
    </div>
 
</div>
 

	
 
<script type="text/javascript">
 
pyroutes.register('admin_settings_my_pullrequests', "${url('admin_settings_my_pullrequests')}", []);
 

	
 
var show_perms = function(e){
 
    YUD.addClass('show_perms', 'current');
 
    YUD.removeClass('show_my','current');
 
    YUD.removeClass('show_pullrequests','current');
 

	
 
    YUD.setStyle('my_container','display','none');
 
    YUD.setStyle('pullrequests_container','display','none');
 
    YUD.setStyle('perms_container','display','');
 
    YUD.setStyle('q_filter','display','none');
 
}
 
YUE.on('show_perms','click',function(e){
 
@@ -136,26 +137,33 @@ YUE.on('show_my','click',function(e){
 
})
 

	
 
var show_pullrequests = function(e){
 
    YUD.addClass('show_pullrequests', 'current');
 
    YUD.removeClass('show_my','current');
 
    YUD.removeClass('show_perms','current');
 

	
 
    YUD.setStyle('my_container','display','none');
 
    YUD.setStyle('perms_container','display','none');
 
    YUD.setStyle('pullrequests_container','display','');
 
    YUD.setStyle('q_filter','display','none');
 

	
 
    var url = "${h.url('admin_settings_my_pullrequests')}";
 
    ypjax(url, 'pullrequests_container');
 
    var url = pyroutes.url('admin_settings_my_pullrequests');
 
    if(YUD.get('show_closed') && YUD.get('show_closed').checked) {
 
        var url = pyroutes.url('admin_settings_my_pullrequests', {'pr_show_closed': '1'});
 
    }
 
    ypjax(url, 'pullrequests_container', function(){
 
        YUE.on('show_closed','change',function (e) {
 
            show_pullrequests(e);
 
        });
 
    });
 
}
 
YUE.on('show_pullrequests','click',function(e){
 
    show_pullrequests(e)
 
})
 

	
 
var tabs = {
 
    'perms': show_perms,
 
    'my': show_my,
 
    'pullrequests': show_pullrequests
 
}
 
var url = location.href.split('#');
 
if (url[1]) {
 
@@ -261,15 +269,16 @@ function table_renderer(data){
 
      YUE.on('q_filter','click',function(){
 
          if(!YUD.hasClass('q_filter', 'loaded')){
 
              YUD.get('q_filter').value = '';
 
              //TODO: load here full list later to do search within groups
 
              YUD.addClass('q_filter', 'loaded');
 
          }
 
       });
 

	
 
      YUE.on('q_filter','keyup',function (e) {
 
          clearTimeout(filterTimeout);
 
          filterTimeout = setTimeout(updateFilter,600);
 
      });
 

	
 
    }
 
</script>
 
</%def>
rhodecode/templates/admin/users/user_edit_my_account_pullrequests.html
Show inline comments
 

	
 
%if c.show_closed:
 
  ${h.checkbox('show_closed',checked="checked", label=_('Show closed pull requests'))}
 
%else:
 
  ${h.checkbox('show_closed',label=_('Show closed pull requests'))}
 
%endif
 
<div class="pullrequests_section_head">${_('Opened by me')}</div>
 
<ul>
 
    %if c.my_pull_requests:
 
      %for pull_request in c.my_pull_requests:
 
      <li>
 
        <div style="height: 12px">
 
          <div style="float:left">
 
          %if pull_request.is_closed():
 
              <img src="${h.url('/images/icons/lock_go.png')}" title="${_('Closed')}"/>
 
          %endif
 
          <img src="${h.url('/images/icons/flag_status_%s.png' % str(pull_request.last_review_status))}" />
 
          <a href="${h.url('pullrequest_show',repo_name=pull_request.other_repo.repo_name,pull_request_id=pull_request.pull_request_id)}">
rhodecode/templates/admin/users_groups/users_group_add.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Add users group')} - ${c.rhodecode_name}
 
    ${_('Add user group')} - ${c.rhodecode_name}
 
</%def>
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${h.link_to(_('Users groups'),h.url('users_groups'))}
 
    ${h.link_to(_('User groups'),h.url('users_groups'))}
 
    &raquo;
 
    ${_('add new users group')}
 
    ${_('add new user group')}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('admin')}
 
</%def>
 

	
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
rhodecode/templates/admin/users_groups/users_group_edit.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Edit users group')} ${c.users_group.users_group_name} - ${c.rhodecode_name}
 
    ${_('Edit user group')} ${c.users_group.users_group_name} - ${c.rhodecode_name}
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${h.link_to(_('UsersGroups'),h.url('users_groups'))}
 
    ${h.link_to(_('UserGroups'),h.url('users_groups'))}
 
    &raquo;
 
    ${_('edit')} "${c.users_group.users_group_name}"
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('admin')}
 
</%def>
 

	
 
<%def name="main()">
 
<div class="box box-left">
 
    <!-- box / title -->
 
    <div class="title">
rhodecode/templates/admin/users_groups/users_groups.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Users groups administration')} - ${c.rhodecode_name}
 
    ${_('User groups administration')} - ${c.rhodecode_name}
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))}
 
    &raquo;
 
    ${_('users groups')}
 
    ${_('user groups')}
 
</%def>
 

	
 
<%def name="page_nav()">
 
    ${self.menu('admin')}
 
</%def>
 

	
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
        <ul class="links">
 
@@ -35,21 +35,21 @@
 
            <th class="left">${_('members')}</th>
 
            <th class="left">${_('active')}</th>
 
            <th class="left">${_('action')}</th>
 
        </tr>
 
            %for cnt,u_group in enumerate(c.users_groups_list):
 
                <tr class="parity${cnt%2}">
 
                    <td>${h.link_to(u_group.users_group_name,h.url('edit_users_group', id=u_group.users_group_id))}</td>
 
                    <td><span class="tooltip" title="${h.tooltip(', '.join(map(h.safe_unicode,[x.user.username for x in u_group.members[:50]])))}">${len(u_group.members)}</span></td>
 
                    <td>${h.bool2icon(u_group.users_group_active)}</td>
 
                    <td>
 
                        ${h.form(url('users_group', id=u_group.users_group_id),method='delete')}
 
                            ${h.submit('remove_',_('delete'),id="remove_group_%s" % u_group.users_group_id,
 
                            class_="delete_icon action_button",onclick="return  confirm('"+_('Confirm to delete this users group: %s') % u_group.users_group_name+"');")}
 
                            class_="delete_icon action_button",onclick="return  confirm('"+_('Confirm to delete this user group: %s') % u_group.users_group_name+"');")}
 
                        ${h.end_form()}
 
                    </td>
 
                </tr>
 
            %endfor
 
        </table>
 
    </div>
 
</div>
 
</%def>
rhodecode/templates/base/base.html
Show inline comments
 
modified file chmod 100644 => 100755
 
@@ -62,27 +62,27 @@
 
</%def>
 

	
 
<%def name="context_bar(current=None)">
 
   %if c.repo_name:
 
    ${repo_context_bar(current)}
 
   %endif
 
</%def>
 

	
 
<%def name="admin_menu()">
 
  <ul class="admin_menu">
 
      <li>${h.link_to(_('admin journal'),h.url('admin_home'),class_='journal')}</li>
 
      <li>${h.link_to(_('repositories'),h.url('repos'),class_='repos')}</li>
 
      <li>${h.link_to(_('repositories groups'),h.url('repos_groups'),class_='repos_groups')}</li>
 
      <li>${h.link_to(_('repository groups'),h.url('repos_groups'),class_='repos_groups')}</li>
 
      <li>${h.link_to(_('users'),h.url('users'),class_='users')}</li>
 
      <li>${h.link_to(_('users groups'),h.url('users_groups'),class_='groups')}</li>
 
      <li>${h.link_to(_('user groups'),h.url('users_groups'),class_='groups')}</li>
 
      <li>${h.link_to(_('permissions'),h.url('edit_permission',id='default'),class_='permissions')}</li>
 
      <li>${h.link_to(_('ldap'),h.url('ldap_home'),class_='ldap')}</li>
 
      <li>${h.link_to(_('defaults'),h.url('defaults'),class_='defaults')}</li>
 
      <li class="last">${h.link_to(_('settings'),h.url('admin_settings'),class_='settings')}</li>
 
  </ul>
 
</%def>
 

	
 
<%def name="admin_menu_simple()">
 
  <ul>
 
      <li>${h.link_to(_('repositories groups'),h.url('repos_groups'),class_='repos_groups')}</li>
 
  </ul>
 
</%def>
 
@@ -224,34 +224,34 @@
 
  <div class="user-menu">
 
      <div id="quick_login">
 
        %if c.rhodecode_user.username == 'default':
 
            <h4>${_('Login to your account')}</h4>
 
            ${h.form(h.url('login_home',came_from=h.url.current()))}
 
            <div class="form">
 
                <div class="fields">
 
                    <div class="field">
 
                        <div class="label">
 
                            <label for="username">${_('Username')}:</label>
 
                        </div>
 
                        <div class="input">
 
                            ${h.text('username',class_='focus',size=40)}
 
                            ${h.text('username',class_='focus')}
 
                        </div>
 

	
 
                    </div>
 
                    <div class="field">
 
                        <div class="label">
 
                            <label for="password">${_('Password')}:</label>
 
                        </div>
 
                        <div class="input">
 
                            ${h.password('password',class_='focus',size=40)}
 
                            ${h.password('password',class_='focus')}
 
                        </div>
 

	
 
                    </div>
 
                    <div class="buttons">
 
                        <div class="password_forgoten">${h.link_to(_('Forgot password ?'),h.url('reset_password'))}</div>
 
                        <div class="register">
 
                        %if h.HasPermissionAny('hg.admin', 'hg.register.auto_activate', 'hg.register.manual_activate')():
 
                         ${h.link_to(_("Don't have an account ?"),h.url('register'))}
 
                        %endif
 
                        </div>
 
                        <div class="submit">
 
                            ${h.submit('sign_in',_('Log In'),class_="ui-btn xsmall")}
rhodecode/templates/base/root.html
Show inline comments
 
@@ -43,25 +43,28 @@
 
            var TRANSLATION_MAP = {
 
                'add another comment':'${_("add another comment")}',
 
                'Stop following this repository':"${_('Stop following this repository')}",
 
                'Start following this repository':"${_('Start following this repository')}",
 
                'Group':"${_('Group')}",
 
                'members':"${_('members')}",
 
                'loading...':"${_('loading...')}",
 
                'search truncated': "${_('search truncated')}",
 
                'no matching files': "${_('no matching files')}",
 
                'Open new pull request': "${_('Open new pull request')}",
 
                'Open new pull request for selected changesets':  "${_('Open new pull request for selected changesets')}",
 
                'Show selected changes __S -> __E': "${_('Show selected changes __S -> __E')}",
 
                'Show selected change __S': "${_('Show selected change __S')}",
 
                'Selection link': "${_('Selection link')}",
 
                'collapse diff': "${_('collapse diff')}",
 
                'expand diff': "${_('expand diff')}",
 
            };
 
            var _TM = TRANSLATION_MAP;
 

	
 
            var TOGGLE_FOLLOW_URL  = "${h.url('toggle_following')}";
 

	
 
            </script>
 
            <script type="text/javascript" src="${h.url('/js/yui.2.9.js', ver=c.rhodecode_version)}"></script>
 
            <!--[if lt IE 9]>
 
               <script language="javascript" type="text/javascript" src="${h.url('/js/excanvas.min.js')}"></script>
 
            <![endif]-->
 
            <script type="text/javascript" src="${h.url('/js/yui.flot.js', ver=c.rhodecode_version)}"></script>
 
            <script type="text/javascript" src="${h.url('/js/native.history.js', ver=c.rhodecode_version)}"></script>
rhodecode/templates/branches/branches.html
Show inline comments
 
@@ -18,25 +18,25 @@
 
    ${self.menu('branches')}
 
</%def>
 

	
 
<%def name="main()">
 
${self.context_bar('switch-to')}
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <!-- end box / title -->
 
    %if c.repo_branches:
 
    <div class="info_box" id="compare_branches" style="clear: both;padding: 10px 19px;vertical-align: right;text-align: right;"><a href="#" class="ui-btn small">${_('Compare branches')}</a></div>
 
    <div class="info_box" id="compare_branches" style="clear: both;padding: 10px 19px;text-align: right;"><a href="#" class="ui-btn small">${_('Compare branches')}</a></div>
 
    %endif
 
    <div class="table">
 
        <%include file='branches_data.html'/>
 
    </div>
 
</div>
 
<script type="text/javascript">
 
YUE.on('compare_branches','click',function(e){
 
    YUE.preventDefault(e);
 
    var org = YUQ('input[name=compare_org]:checked')[0];
 
    var other = YUQ('input[name=compare_other]:checked')[0];
 

	
 
    if(org && other){
rhodecode/templates/changelog/changelog.html
Show inline comments
 
@@ -24,33 +24,33 @@ ${_('%s Changelog') % c.repo_name} - ${c
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <div class="table">
 
        % if c.pagination:
 
            <div id="graph">
 
                <div id="graph_nodes">
 
                    <canvas id="graph_canvas"></canvas>
 
                </div>
 
                <div id="graph_content">
 
                    <div class="info_box" style="clear: both;padding: 10px 6px;vertical-align: right;text-align: right;">
 
                    <div class="info_box" style="clear: both;padding: 10px 6px;text-align: right;">
 
                    <a href="#" class="ui-btn small" id="rev_range_container" style="display:none"></a>
 
                    <a href="#" class="ui-btn small" id="rev_range_clear" style="display:none">${_('Clear selection')}</a>
 

	
 
                    %if c.rhodecode_db_repo.fork:
 
                        <a title="${_('compare fork with %s' % c.rhodecode_db_repo.fork.repo_name)}" href="${h.url('compare_url',repo_name=c.rhodecode_db_repo.fork.repo_name,org_ref_type='branch',org_ref='default',other_repo=c.repo_name,other_ref_type='branch',other_ref=request.GET.get('branch') or 'default')}" class="ui-btn small">${_('Compare fork with parent')}</a>
 
                        <a title="${_('Compare fork with %s' % c.rhodecode_db_repo.fork.repo_name)}" href="${h.url('compare_url',repo_name=c.rhodecode_db_repo.fork.repo_name,org_ref_type='branch',org_ref='default',other_repo=c.repo_name,other_ref_type='branch',other_ref=request.GET.get('branch') or 'default')}" class="ui-btn small">${_('Compare fork with parent')}</a>
 
                    %endif
 
                    %if h.is_hg(c.rhodecode_repo):
 
                    <a id="open_new_pr" href="${h.url('pullrequest_home',repo_name=c.repo_name)}" class="ui-btn small">${_('open new pull request')}</a>
 
                    <a id="open_new_pr" href="${h.url('pullrequest_form',repo_name=c.repo_name)}" class="ui-btn small">${_('Open new pull request')}</a>
 
                    %endif
 
                    </div>
 
                    <div class="container_header">
 
                        ${h.form(h.url.current(),method='get')}
 
                        <div class="info_box" style="float:left">
 
                          ${h.submit('set',_('Show'),class_="ui-btn")}
 
                          ${h.text('size',size=1,value=c.size)}
 
                          ${_('revisions')}
 
                        </div>
 
                        ${h.end_form()}
 
                    <div style="float:right">${h.select('branch_filter',c.branch_name,c.branch_filters)}</div>
 
                    </div>
 
@@ -63,25 +63,25 @@ ${_('%s Changelog') % c.repo_name} - ${c
 
                            <span class="tooltip" title="${h.tooltip(h.age(cs.date))}"><a href="${h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id)}"><span class="changeset_id">${cs.revision}:<span class="changeset_hash">${h.short_id(cs.raw_id)}</span></span></a></span>
 
                            </div>
 
                            <div class="author">
 
                                <div class="gravatar">
 
                                    <img alt="gravatar" src="${h.gravatar_url(h.email_or_none(cs.author),16)}"/>
 
                                </div>
 
                                <div title="${cs.author}" class="user">${h.shorter(h.person(cs.author),22)}</div>
 
                            </div>
 
                            <div class="date">${h.fmt_date(cs.date)}</div>
 
                        </div>
 
                        <div class="mid">
 
                            <div class="message">${h.urlify_commit(cs.message, c.repo_name,h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id))}</div>
 
                            <div class="expand"><span class="expandtext">&darr; ${_('show more')} &darr;</span></div>
 
                            <div class="expand"><span class="expandtext">&darr; ${_('Show more')} &darr;</span></div>
 
                        </div>
 
                        <div class="right">
 
                                    <div class="changes">
 
                                        <div id="changed_total_${cs.raw_id}" style="float:right;" class="changed_total tooltip" title="${h.tooltip(_('Affected number of files, click to show more details'))}">${len(cs.affected_files)}</div>
 
                                        <div class="comments-container">
 
                                        %if len(c.comments.get(cs.raw_id,[])) > 0:
 
                                            <div class="comments-cnt" title="${('comments')}">
 
                                              <a href="${h.url('changeset_home',repo_name=c.repo_name,revision=cs.raw_id,anchor='comment-%s' % c.comments[cs.raw_id][0].comment_id)}">
 
                                               <div class="comments-cnt">${len(c.comments[cs.raw_id])}</div>
 
                                               <img src="${h.url('/images/icons/comments.png')}">
 
                                              </a>
 
                                            </div>
 
@@ -154,59 +154,39 @@ ${_('%s Changelog') % c.repo_name} - ${c
 
                    YUE.on(checkboxes,'click',function(e){
 
                        var clicked_cb = e.currentTarget;
 
                        var checked_checkboxes = [];
 
                        for (pos in checkboxes){
 
                            if(checkboxes[pos].checked){
 
                                checked_checkboxes.push(checkboxes[pos]);
 
                            }
 
                        }
 
                        if(YUD.get('open_new_pr')){
 
                          if(checked_checkboxes.length>0){
 
                            // modify open pull request to show we have selected cs
 
                            YUD.get('open_new_pr').innerHTML = _TM['Open new pull request for selected changesets'];
 

	
 
                          }else{
 
                            YUD.get('open_new_pr').innerHTML = _TM['Open new pull request'];
 
                          }
 
                        }
 

	
 
                        if(checked_checkboxes.length>0){
 
                            var rev_end = checked_checkboxes[0].name;
 
                            var rev_start = checked_checkboxes[checked_checkboxes.length-1].name;
 

	
 
                            // now select all checkboxes in the middle.
 
                            var checked = false;
 
                            for (var i=0; i<checkboxes.length; i++){
 
                                var cb = checkboxes[i];
 
                                var rev = cb.name;
 

	
 
                                if (rev == rev_end){
 
                                    checked = true;
 
                                }
 
                                if (checked){
 
                                    cb.checked = true;
 
                                }
 
                                else{
 
                                    cb.checked = false;
 
                                }
 
                                if (rev == rev_start){
 
                                    checked = false;
 
                                }
 

	
 
                            }
 

	
 
                            var url = url_tmpl.replace('__REVRANGE__',
 
                                    rev_start+'...'+rev_end);
 

	
 
                            var link = _TM['Show selected changes __S -> __E'];
 
                            var link = (rev_start == rev_end)
 
                                ? _TM['Show selected change __S']
 
                                : _TM['Show selected changes __S -> __E'];
 

	
 
                            link = link.replace('__S',rev_start.substr(0,6));
 
                            link = link.replace('__E',rev_end.substr(0,6));
 
                            YUD.get('rev_range_container').href = url;
 
                            YUD.get('rev_range_container').innerHTML = link;
 
                            YUD.setStyle('rev_range_container','display','');
 
                            YUD.setStyle('rev_range_clear','display','');
 

	
 
                            YUD.get('open_new_pr').href = pr_tmpl + '?rev_start={0}&rev_end={1}'.format(rev_start,rev_end);
 

	
 
                        }
 
                        else{
 
                            YUD.setStyle('rev_range_container','display','none');
rhodecode/templates/changeset/diff_block.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
##usage:
 
## <%namespace name="diff_block" file="/changeset/diff_block.html"/>
 
## ${diff_block.diff_block(change)}
 
##
 
<%def name="diff_block(change)">
 

	
 
<div class="diff-collapse">
 
    <span target="${'diff-container-%s' % (id(change))}" class="diff-collapse-button">&uarr; ${_('collapse diff')} &uarr;</span>
 
</div>
 
<div class="diff-container" id="${'diff-container-%s' % (id(change))}">
 
%for FID,(cs1, cs2, change, path, diff, stats) in change.iteritems():
 
    ##%if op !='removed':
 
    <div id="${FID}_target" style="clear:both;margin-top:25px"></div>
 
    <div id="${FID}" class="diffblock  margined comm">
 
        <div class="code-header">
 
            <div class="changeset_header">
 
                <div class="changeset_file">
 
                    ${h.link_to_if(change!='removed',h.safe_unicode(path),h.url('files_home',repo_name=c.repo_name,
 
                    revision=cs2,f_path=h.safe_unicode(path)))}
 
                </div>
 
                <div class="diff-actions">
 
                  <a href="${h.url('files_diff_home',repo_name=c.repo_name,f_path=h.safe_unicode(path),diff2=cs2,diff1=cs1,diff='diff',fulldiff=1)}" class="tooltip" title="${h.tooltip(_('show full diff for this file'))}"><img class="icon" src="${h.url('/images/icons/page_white_go.png')}"/></a>
 
@@ -28,36 +31,36 @@
 
                  ${h.checkbox('',checked="checked",class_="show-inline-comments",id_for=h.FID(cs2,path))}
 
                  </label>
 
                </span>
 
            </div>
 
        </div>
 
        <div class="code-body">
 
            <div class="full_f_path" path="${h.safe_unicode(path)}"></div>
 
            ${diff|n}
 
        </div>
 
    </div>
 
    ##%endif
 
%endfor
 

	
 
</div>
 
</%def>
 

	
 
<%def name="diff_block_simple(change)">
 

	
 
  %for op,filenode_path,diff in change:
 
    <div id="${h.FID('',filenode_path)}_target" style="clear:both;margin-top:25px"></div>
 
    <div id="${h.FID('',filenode_path)}" class="diffblock  margined comm">
 
      <div class="code-header">
 
          <div class="changeset_header">
 
              <div class="changeset_file">
 
                  ${h.safe_unicode(filenode_path)} |
 
                  <a class="spantag" href="${h.url('files_home', repo_name=c.repo_name, f_path=filenode_path, revision=c.org_ref)}">${c.org_ref_type}@${c.org_ref}</a> -&gt;
 
                  <a class="spantag" href="${h.url('files_home', repo_name=c.repo_name, f_path=filenode_path, revision=c.other_ref)}">${c.other_ref_type}@${c.other_ref}</a>
 
                  <a class="spantag" href="${h.url('files_home', repo_name=c.repo_name, f_path=filenode_path, revision=c.org_ref)}" title="${_('show file at latest version in this repo')}">${c.org_ref_type}@${h.short_id(c.org_ref) if c.org_ref_type=='rev' else c.org_ref}</a> -&gt;
 
                  <a class="spantag" href="${h.url('files_home', repo_name=c.repo_name, f_path=filenode_path, revision=c.other_ref)}" title="${_('show file at initial version in this repo')}">${c.other_ref_type}@${h.short_id(c.other_ref) if c.other_ref_type=='rev' else c.other_ref}</a>
 
              </div>
 
          </div>
 
      </div>
 
        <div class="code-body">
 
            <div class="full_f_path" path="${h.safe_unicode(filenode_path)}"></div>
 
            ${diff|n}
 
        </div>
 
    </div>
 
  %endfor
 
</%def>
rhodecode/templates/email_templates/changeset_comment.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="main.html"/>
 

	
 
<h4>${subject}</h4>
 

	
 
##message from user goes here
 
<p>
 
${cs_comment_user}: <br/>
 
${body}
 
</p>
 
%if status_change:
 
    <span>${_('New status')} -&gt; ${status_change}</span>
 
%endif
 
<div>${_('View this comment here')}: ${cs_comment_url}</div>
 

	
 
% if status_change is not None:
 
<div>
 
    ${_('New status')} -&gt; ${status_change}
 
</div>
 
% endif
 
<pre>
 
${_('Repo')}: ${cs_target_repo}
 
${_('Changeset')}: ${h.short_id(raw_id)}
 
${_('desc')}: ${h.shorter(message, 256)}
 
</pre>
rhodecode/templates/email_templates/password_reset.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="main.html"/>
 

	
 
${_('Hello')} ${user}
 

	
 
${_('We received a request to create a new password for your account.')}
 

	
 
${_('You can generate it by clicking following URL')}:
 

	
 
<h4>${_('Hello %s') % user}</h4>
 
<div>${_('We received a request to create a new password for your account.')}</div>
 
<div>${_('You can generate it by clicking following URL')}:</div>
 
<pre>
 
${reset_url}
 

	
 
${_("If you didn't request new password please ignore this email.")}
 
</pre>
 
<br/>
 
${_("If you did not request new password please ignore this email.")}
rhodecode/templates/email_templates/pull_request.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="main.html"/>
 

	
 
${_('User %s opened pull request for repository %s and wants you to review changes.') % (('<b>%s</b>' % pr_user_created),pr_repo_url) |n}
 
<div>${_('View this pull request here')}: ${pr_url}</div>
 
<div>${_('title')}: ${pr_title}</div>
 
<div>${_('description')}:</div>
 
<p>
 
${body}
 
</p>
 

	
 
<div>${_('revisions for reviewing')}</div>
 
<ul>
 
%for r in pr_revisions:
 
    <li>${r}</li>
 
<pre>
 
%for r,r_msg in pr_revisions:
 
${h.short_id(r)}:
 
    ${h.shorter(r_msg, 256)}
 

	
 
%endfor
 
</ul>
 
</pre>
rhodecode/templates/email_templates/pull_request_comment.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="main.html"/>
 

	
 
${_('User %s commented on pull request #%s for repository %s') % ('<b>%s</b>' % pr_comment_user, pr_id, pr_target_repo) |n}
 
${_('Pull request #%s for repository %s') % (pr_id, pr_target_repo) |n}
 
##message from user goes here
 
<p>
 
${pr_comment_user}: <br/>
 
${body}
 
</p>
 
<div>${_('View this comment here')}: ${pr_comment_url}</div>
 

	
 
<p>
 
${body}
 

	
 
%if status_change:
 
    <span>${_('New status')} -&gt; ${status_change}</span>
 
    %if closing_pr:
 
       <span>${_('Closing pull request with status')} -&gt; ${status_change}</span>
 
    %else:
 
       <span>${_('New status')} -&gt; ${status_change}</span>
 
    %endif
 
%endif
 
</p>
rhodecode/templates/files/files_source.html
Show inline comments
 
@@ -77,26 +77,29 @@ YUE.onDOMReady(function(){
 
                var start = parseInt(_range[0]);
 
                var end = parseInt(_range[1]);
 
                if (start < end){
 
                    for(var i=start;i<=end;i++){
 
                        h_lines.push(i);
 
                    }
 
                }
 
            }
 
            else{
 
                h_lines.push(parseInt(highlight_ranges[pos]));
 
            }
 
      }
 
    highlight_lines(h_lines);
 

	
 
	  highlight_lines(h_lines);
 
	  var _first_line= YUD.get('L'+h_lines[0]);
 
	  if(_first_line){
 
		  _first_line.scrollIntoView()
 
	  }
 
    }
 

	
 
    // select code link event
 
    YUE.on('hlcode', 'mouseup', getSelectionLink);
 

	
 
    //load history of file
 
    YUE.on('load_node_history', 'click', function(e){
 
        var _url = node_history_url.replace('__REV__','${c.file_changeset.raw_id}').replace('__FPATH__', '${c.f_path}');
 
        ypjax(_url, 'node_history', function(o){
 
            tooltip_activate();
 
        })
 
    });
rhodecode/templates/index_base.html
Show inline comments
 
@@ -39,25 +39,25 @@
 
                      <tr>
 
                          <th class="left"><a href="#">${_('Group name')}</a></th>
 
                          <th class="left"><a href="#">${_('Description')}</a></th>
 
                          ##<th class="left"><a href="#">${_('Number of repositories')}</a></th>
 
                      </tr>
 
                  </thead>
 

	
 
                  ## REPO GROUPS
 
                  % for gr in c.groups:
 
                    <tr>
 
                        <td>
 
                            <div style="white-space: nowrap">
 
                            <img class="icon" alt="${_('Repositories group')}" src="${h.url('/images/icons/database_link.png')}"/>
 
                            <img class="icon" alt="${_('Repository group')}" src="${h.url('/images/icons/database_link.png')}"/>
 
                            ${h.link_to(gr.name,url('repos_group_home',group_name=gr.group_name))}
 
                            </div>
 
                        </td>
 
                        %if c.visual.stylify_metatags:
 
                            <td>${h.urlify_text(h.desc_stylize(gr.group_description))}</td>
 
                        %else:
 
                            <td>${gr.group_description}</td>
 
                        %endif
 
                        ## this is commented out since for multi nested repos can be HEAVY!
 
                        ## in number of executed queries during traversing uncomment at will
 
                        ##<td><b>${gr.repositories_recursive_count}</b></td>
 
                    </tr>
rhodecode/templates/login.html
Show inline comments
 
@@ -22,34 +22,34 @@
 
    </div>
 
    <div class="inner">
 
        ${h.form(h.url.current(came_from=c.came_from))}
 
        <div class="form">
 
            <!-- fields -->
 

	
 
            <div class="fields">
 
                <div class="field">
 
                    <div class="label">
 
                        <label for="username">${_('Username')}:</label>
 
                    </div>
 
                    <div class="input">
 
                        ${h.text('username',class_='focus',size=40)}
 
                        ${h.text('username',class_='focus large')}
 
                    </div>
 

	
 
                </div>
 
                <div class="field">
 
                    <div class="label">
 
                        <label for="password">${_('Password')}:</label>
 
                    </div>
 
                    <div class="input">
 
                        ${h.password('password',class_='focus',size=40)}
 
                        ${h.password('password',class_='focus large')}
 
                    </div>
 

	
 
                </div>
 
                <div class="field">
 
                    <div class="checkbox">
 
                        <input type="checkbox" id="remember" name="remember" />
 
                        <label for="remember">${_('Remember me')}</label>
 
                    </div>
 
                </div>
 
                <div class="buttons">
 
                    ${h.submit('sign_in',_('Sign In'),class_="ui-btn large")}
 
                </div>
rhodecode/templates/pullrequests/pullrequest.html
Show inline comments
 
@@ -21,39 +21,39 @@
 
    </div>
 
    ${h.form(url('pullrequest', repo_name=c.repo_name), method='post', id='pull_request_form')}
 
    <div style="float:left;padding:0px 30px 30px 30px">
 
        <input type="hidden" name="rev_start" value="${request.GET.get('rev_start')}" />
 
        <input type="hidden" name="rev_end" value="${request.GET.get('rev_end')}" />
 

	
 
        ##ORG
 
        <div style="float:left">
 
            <div>
 
                <span style="font-size: 20px">
 
                ${h.select('org_repo','',c.org_repos,class_='refs')}:${h.select('org_ref',c.default_org_ref,c.org_refs,class_='refs')}
 
                </span>
 
                 <div style="padding:5px 3px 3px 42px;">${c.rhodecode_db_repo.description}</div>
 
                 <div style="padding:5px 3px 3px 20px;">${c.rhodecode_db_repo.description}</div>
 
            </div>
 
            <div style="clear:both;padding-top: 10px"></div>
 
        </div>
 
          <div style="float:left;font-size:24px;padding:0px 20px">
 
          <img height=32 width=32 src="${h.url('/images/arrow_right_64.png')}"/>
 
          </div>
 

	
 
        ##OTHER, most Probably the PARENT OF THIS FORK
 
        <div style="float:left">
 
            <div>
 
                <span style="font-size: 20px">
 
                ${h.select('other_repo',c.default_other_repo,c.other_repos,class_='refs')}:${h.select('other_ref',c.default_other_ref,c.default_other_refs,class_='refs')}
 
                </span>
 
                 <div id="other_repo_desc" style="padding:5px 3px 3px 42px;"></div>
 
                 <div id="other_repo_desc" style="padding:5px 3px 3px 20px;"></div>
 
            </div>
 
            <div style="clear:both;padding-top: 10px"></div>
 
        </div>
 
       <div style="clear:both;padding-top: 10px"></div>
 
       ## overview pulled by ajax
 
       <div style="float:left" id="pull_request_overview"></div>
 
       <div style="float:left;clear:both;padding:10px 10px 10px 0px;display:none">
 
            <a id="pull_request_overview_url" href="#">${_('Detailed compare view')}</a>
 
       </div>
 
     </div>
 
    <div style="float:left; border-left:1px dashed #eee">
 
        <h4>${_('Pull request reviewers')}</h4>
 
@@ -137,51 +137,52 @@
 
                         other_ref='__org_ref__',
 
                         as_form=True,
 
                         rev_start=request.GET.get('rev_start',''),
 
                         rev_end=request.GET.get('rev_end',''))}";
 
      var org_repo = YUQ('#pull_request_form #org_repo')[0].value;
 
      var org_ref = YUQ('#pull_request_form #org_ref')[0].value.split(':');
 

	
 
      var other_repo = YUQ('#pull_request_form #other_repo')[0].value;
 
      var other_ref = YUQ('#pull_request_form #other_ref')[0].value.split(':');
 

	
 
      var select_refs = YUQ('#pull_request_form select.refs')
 
      var rev_data = {
 
    	  'org_repo': org_repo,
 
    	  'org_ref': org_ref[1],
 
    	  'org_ref_type': org_ref[0],
 
    	  'other_repo': other_repo,
 
          'other_ref': other_ref[1],
 
          'other_ref_type': other_ref[0],
 
          'org_repo': org_repo,
 
          'org_ref': org_ref[2],
 
          'org_ref_type': 'rev',
 
          'other_repo': other_repo,
 
          'other_ref': other_ref[2],
 
          'other_ref_type': 'rev',
 
      }; // gather the org/other ref and repo here
 

	
 
      for (k in rev_data){
 
    	  url = url.replace('__'+k+'__',rev_data[k]);
 
          url = url.replace('__'+k+'__',rev_data[k]);
 
      }
 

	
 
      YUD.get('pull_request_overview').innerHTML = "${_('Loading ...')}";
 
      YUD.get('pull_request_overview_url').href = url; // shouldn't have as_form ... but ...
 
      YUD.setStyle(YUD.get('pull_request_overview_url').parentElement,'display','');
 
      ypjax(url,'pull_request_overview', function(data){
 
          var sel_box = YUQ('#pull_request_form #other_repo')[0];
 
          var repo_name = sel_box.options[sel_box.selectedIndex].value;
 
          var _data = other_repos_info[repo_name];
 
          YUD.get('pull_request_overview_url').href = url;
 
          YUD.setStyle(YUD.get('pull_request_overview_url').parentElement,'display','');
 
          YUD.get('other_repo_desc').innerHTML = other_repos_info[repo_name]['description'];
 
          YUD.get('other_ref').innerHTML = other_repos_info[repo_name]['revs'];
 
          // select back the revision that was just compared
 
          setSelectValue(YUD.get('other_ref'), rev_data['other_ref']);
 
          // reset && add the reviewer based on selected repo
 
          YUD.get('review_members').innerHTML = '';
 
          addReviewMember(_data.user.user_id, _data.user.firstname,
 
        		          _data.user.lastname, _data.user.username,
 
        		          _data.user.gravatar_link);
 
                          _data.user.lastname, _data.user.username,
 
                          _data.user.gravatar_link);
 
      })
 
  }
 

	
 
  ## refresh automatically when something changes (org_repo can't change)
 

	
 
  YUE.on('org_ref', 'change', function(e){
 
     loadPreview();
 
  });
 

	
 
  YUE.on('other_repo', 'change', function(e){
 
      var repo_name = e.currentTarget.value;
 
      // replace the <select> of changed repo
rhodecode/templates/pullrequests/pullrequest_show.html
Show inline comments
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${c.repo_name} ${_('Pull request #%s') % c.pull_request.pull_request_id}
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_(u'Home'),h.url('/'))}
 
    &raquo;
 
    ${h.link_to(c.repo_name,h.url('changelog_home',repo_name=c.repo_name))}
 
    ${h.repo_link(c.rhodecode_db_repo.groups_and_repo)}
 
    &raquo;
 
    ${_('Pull request #%s') % c.pull_request.pull_request_id}
 
</%def>
 

	
 
<%def name="main()">
 

	
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
        %if c.pull_request.is_closed():
 
        <div style="padding:10px; font-size:22px;width:100%;text-align: center; color:#88D882">${_('Closed %s') % (h.age(c.pull_request.updated_on))} ${_('with status %s') % h.changeset_status_lbl(c.current_changeset_status)}</div>
 
        %endif
 
    <h3>${_('Title')}: ${c.pull_request.title}</h3>
 
    <h3>
 
    %if c.pull_request.is_closed():
 
        <img src="${h.url('/images/icons/lock_go.png')}" title="${_('Closed')}"/>
 
    %endif
 
    <img src="${h.url('/images/icons/flag_status_%s.png' % str(c.pull_request.last_review_status))}" />
 
    ${_('Title')}: ${c.pull_request.title}</h3>
 

	
 
    <div class="form">
 
      <div id="summary" class="fields">
 
         <div class="field">
 
          <div class="label-summary">
 
              <label>${_('Review status')}:</label>
 
          </div>
 
          <div class="input">
 
            <div class="changeset-status-container" style="float:none;clear:both">
 
            %if c.current_changeset_status:
 
              <div title="${_('Pull request status')}" class="changeset-status-lbl">${h.changeset_status_lbl(c.current_changeset_status)}</div>
 
              <div class="changeset-status-ico" style="padding:1px 4px"><img src="${h.url('/images/icons/flag_status_%s.png' % c.current_changeset_status)}" /></div>
rhodecode/templates/switch_to_list.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<li>
 
    ${h.link_to('%s (%s)' % (_('branches'),len(c.rhodecode_repo.branches.values()),),h.url('branches_home',repo_name=c.repo_name),class_='branches childs')}
 
    <ul>
 
    %if c.rhodecode_repo.branches.values():
 
        %for cnt,branch in enumerate(c.rhodecode_repo.branches.items()):
 
            <li><div><pre>${h.link_to('%s - %s' % (branch[0],h.short_id(branch[1])),h.url('files_home',repo_name=c.repo_name,revision=branch[0]))}</pre></div></li>
 
            <li><div><pre>${h.link_to('%s - %s' % (branch[0],h.short_id(branch[1])),h.url('files_home',repo_name=c.repo_name,revision=(branch[0] if '/' not in branch[0] else branch[1]), at=branch[0]))}</pre></div></li>
 
        %endfor
 
    %else:
 
        <li>${h.link_to(_('There are no branches yet'),'#')}</li>
 
    %endif
 
    </ul>
 
</li>
 
<li>
 
    ${h.link_to('%s (%s)' % (_('tags'),len(c.rhodecode_repo.tags.values()),),h.url('tags_home',repo_name=c.repo_name),class_='tags childs')}
 
    <ul>
 
    %if c.rhodecode_repo.tags.values():
 
        %for cnt,tag in enumerate(c.rhodecode_repo.tags.items()):
 
         <li><div><pre>${h.link_to('%s - %s' % (tag[0],h.short_id(tag[1])),h.url('files_home',repo_name=c.repo_name,revision=tag[0]))}</pre></div></li>
 
         <li><div><pre>${h.link_to('%s - %s' % (tag[0],h.short_id(tag[1])),h.url('files_home',repo_name=c.repo_name,revision=(tag[0] if '/' not in tag[0] else tag[1]), at=tag[0]))}</pre></div></li>
 
        %endfor
 
    %else:
 
        <li>${h.link_to(_('There are no tags yet'),'#')}</li>
 
    %endif
 
    </ul>
 
</li>
 
%if c.rhodecode_repo.alias == 'hg':
 
<li>
 
    ${h.link_to('%s (%s)' % (_('bookmarks'),len(c.rhodecode_repo.bookmarks.values()),),h.url('bookmarks_home',repo_name=c.repo_name),class_='bookmarks childs')}
 
    <ul>
 
    %if c.rhodecode_repo.bookmarks.values():
 
        %for cnt,book in enumerate(c.rhodecode_repo.bookmarks.items()):
 
         <li><div><pre>${h.link_to('%s - %s' % (book[0],h.short_id(book[1])),h.url('files_home',repo_name=c.repo_name,revision=book[1]))}</pre></div></li>
 
         <li><div><pre>${h.link_to('%s - %s' % (book[0],h.short_id(book[1])),h.url('files_home',repo_name=c.repo_name,revision=(book[0] if '/' not in book[0] else book[1]), at=book[0]))}</pre></div></li>
 
        %endfor
 
    %else:
 
        <li>${h.link_to(_('There are no bookmarks yet'),'#')}</li>
 
    %endif
 
    </ul>
 
</li>
 
%endif
rhodecode/templates/tags/tags.html
Show inline comments
 
@@ -18,25 +18,25 @@
 
<%def name="page_nav()">
 
    ${self.menu('tags')}
 
</%def>
 
<%def name="main()">
 
${self.context_bar('switch-to')}
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <!-- end box / title -->
 
    %if c.repo_tags:
 
    <div class="info_box" id="compare_tags" style="clear: both;padding: 10px 19px;vertical-align: right;text-align: right;"><a href="#" class="ui-btn small">${_('Compare tags')}</a></div>
 
    <div class="info_box" id="compare_tags" style="clear: both;padding: 10px 19px;text-align: right;"><a href="#" class="ui-btn small">${_('Compare tags')}</a></div>
 
    %endif
 
    <div class="table">
 
        <%include file='tags_data.html'/>
 
    </div>
 
</div>
 
<script type="text/javascript">
 
YUE.on('compare_tags','click',function(e){
 
    YUE.preventDefault(e);
 
    var org = YUQ('input[name=compare_org]:checked')[0];
 
    var other = YUQ('input[name=compare_other]:checked')[0];
 

	
 
    if(org && other){
rhodecode/tests/api/api_base.py
Show inline comments
 
from __future__ import with_statement
 
import random
 
import mock
 

	
 
from rhodecode.tests import *
 
from rhodecode.lib.compat import json
 
from rhodecode.lib.auth import AuthUser
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.meta import Session
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.model.db import Repository
 

	
 
API_URL = '/_admin/api'
 

	
 

	
 
def _build_data(apikey, method, **kw):
 
    """
 
    Builds API data with given random ID
 

	
 
@@ -34,37 +34,37 @@ jsonify = lambda obj: json.loads(json.du
 

	
 

	
 
def crash(*args, **kwargs):
 
    raise Exception('Total Crash !')
 

	
 

	
 
def api_call(test_obj, params):
 
    response = test_obj.app.post(API_URL, content_type='application/json',
 
                                 params=params)
 
    return response
 

	
 

	
 
TEST_USERS_GROUP = 'test_users_group'
 
TEST_USER_GROUP = 'test_users_group'
 

	
 

	
 
def make_users_group(name=TEST_USERS_GROUP):
 
    gr = UsersGroupModel().create(name=name)
 
    UsersGroupModel().add_user_to_group(users_group=gr,
 
def make_users_group(name=TEST_USER_GROUP):
 
    gr = UserGroupModel().create(name=name)
 
    UserGroupModel().add_user_to_group(users_group=gr,
 
                                        user=TEST_USER_ADMIN_LOGIN)
 
    Session().commit()
 
    return gr
 

	
 

	
 
def destroy_users_group(name=TEST_USERS_GROUP):
 
    UsersGroupModel().delete(users_group=name, force=True)
 
def destroy_users_group(name=TEST_USER_GROUP):
 
    UserGroupModel().delete(users_group=name, force=True)
 
    Session().commit()
 

	
 

	
 
def create_repo(repo_name, repo_type, owner=None):
 
    # create new repo
 
    form_data = _get_repo_create_params(
 
                    repo_name_full=repo_name,
 
                    repo_description='description %s' % repo_name,
 
                )
 
    cur_user = UserModel().get_by_username(owner or TEST_USER_ADMIN_LOGIN)
 
    r = RepoModel().create(form_data, cur_user)
 
    Session().commit()
 
@@ -990,169 +990,169 @@ class BaseTestApi(object):
 
                                    repoid=self.REPO,
 
                                    fork_name=fork_name,
 
                                    owner=TEST_USER_ADMIN_LOGIN,
 
                                  )
 
        response = api_call(self, params)
 

	
 
        expected = 'failed to fork repository `%s` as `%s`' % (self.REPO,
 
                                                               fork_name)
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    def test_api_get_users_group(self):
 
        id_, params = _build_data(self.apikey, 'get_users_group',
 
                                  usersgroupid=TEST_USERS_GROUP)
 
                                  usersgroupid=TEST_USER_GROUP)
 
        response = api_call(self, params)
 

	
 
        users_group = UsersGroupModel().get_group(TEST_USERS_GROUP)
 
        users_group = UserGroupModel().get_group(TEST_USER_GROUP)
 
        members = []
 
        for user in users_group.members:
 
            user = user.user
 
            members.append(user.get_api_data())
 

	
 
        ret = users_group.get_api_data()
 
        ret['members'] = members
 
        expected = ret
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
    def test_api_get_users_groups(self):
 

	
 
        make_users_group('test_users_group2')
 

	
 
        id_, params = _build_data(self.apikey, 'get_users_groups',)
 
        response = api_call(self, params)
 

	
 
        expected = []
 
        for gr_name in [TEST_USERS_GROUP, 'test_users_group2']:
 
            users_group = UsersGroupModel().get_group(gr_name)
 
        for gr_name in [TEST_USER_GROUP, 'test_users_group2']:
 
            users_group = UserGroupModel().get_group(gr_name)
 
            ret = users_group.get_api_data()
 
            expected.append(ret)
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
        UsersGroupModel().delete(users_group='test_users_group2')
 
        UserGroupModel().delete(users_group='test_users_group2')
 
        Session().commit()
 

	
 
    def test_api_create_users_group(self):
 
        group_name = 'some_new_group'
 
        id_, params = _build_data(self.apikey, 'create_users_group',
 
                                  group_name=group_name)
 
        response = api_call(self, params)
 

	
 
        ret = {
 
            'msg': 'created new users group `%s`' % group_name,
 
            'users_group': jsonify(UsersGroupModel()\
 
            'msg': 'created new user group `%s`' % group_name,
 
            'users_group': jsonify(UserGroupModel()\
 
                                   .get_by_name(group_name)\
 
                                   .get_api_data())
 
        }
 
        expected = ret
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
        destroy_users_group(group_name)
 

	
 
    def test_api_get_users_group_that_exist(self):
 
        id_, params = _build_data(self.apikey, 'create_users_group',
 
                                  group_name=TEST_USERS_GROUP)
 
                                  group_name=TEST_USER_GROUP)
 
        response = api_call(self, params)
 

	
 
        expected = "users group `%s` already exist" % TEST_USERS_GROUP
 
        expected = "user group `%s` already exist" % TEST_USER_GROUP
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    @mock.patch.object(UsersGroupModel, 'create', crash)
 
    @mock.patch.object(UserGroupModel, 'create', crash)
 
    def test_api_get_users_group_exception_occurred(self):
 
        group_name = 'exception_happens'
 
        id_, params = _build_data(self.apikey, 'create_users_group',
 
                                  group_name=group_name)
 
        response = api_call(self, params)
 

	
 
        expected = 'failed to create group `%s`' % group_name
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    def test_api_add_user_to_users_group(self):
 
        gr_name = 'test_group'
 
        UsersGroupModel().create(gr_name)
 
        UserGroupModel().create(gr_name)
 
        Session().commit()
 
        id_, params = _build_data(self.apikey, 'add_user_to_users_group',
 
                                  usersgroupid=gr_name,
 
                                  userid=TEST_USER_ADMIN_LOGIN)
 
        response = api_call(self, params)
 

	
 
        expected = {
 
                    'msg': 'added member `%s` to users group `%s`' % (
 
                    'msg': 'added member `%s` to user group `%s`' % (
 
                                TEST_USER_ADMIN_LOGIN, gr_name
 
                            ),
 
                    'success': True}
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
        UsersGroupModel().delete(users_group=gr_name)
 
        UserGroupModel().delete(users_group=gr_name)
 
        Session().commit()
 

	
 
    def test_api_add_user_to_users_group_that_doesnt_exist(self):
 
        id_, params = _build_data(self.apikey, 'add_user_to_users_group',
 
                                  usersgroupid='false-group',
 
                                  userid=TEST_USER_ADMIN_LOGIN)
 
        response = api_call(self, params)
 

	
 
        expected = 'users group `%s` does not exist' % 'false-group'
 
        expected = 'user group `%s` does not exist' % 'false-group'
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    @mock.patch.object(UsersGroupModel, 'add_user_to_group', crash)
 
    @mock.patch.object(UserGroupModel, 'add_user_to_group', crash)
 
    def test_api_add_user_to_users_group_exception_occurred(self):
 
        gr_name = 'test_group'
 
        UsersGroupModel().create(gr_name)
 
        UserGroupModel().create(gr_name)
 
        Session().commit()
 
        id_, params = _build_data(self.apikey, 'add_user_to_users_group',
 
                                  usersgroupid=gr_name,
 
                                  userid=TEST_USER_ADMIN_LOGIN)
 
        response = api_call(self, params)
 

	
 
        expected = 'failed to add member to users group `%s`' % gr_name
 
        expected = 'failed to add member to user group `%s`' % gr_name
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
        UsersGroupModel().delete(users_group=gr_name)
 
        UserGroupModel().delete(users_group=gr_name)
 
        Session().commit()
 

	
 
    def test_api_remove_user_from_users_group(self):
 
        gr_name = 'test_group_3'
 
        gr = UsersGroupModel().create(gr_name)
 
        UsersGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
 
        gr = UserGroupModel().create(gr_name)
 
        UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
 
        Session().commit()
 
        id_, params = _build_data(self.apikey, 'remove_user_from_users_group',
 
                                  usersgroupid=gr_name,
 
                                  userid=TEST_USER_ADMIN_LOGIN)
 
        response = api_call(self, params)
 

	
 
        expected = {
 
                    'msg': 'removed member `%s` from users group `%s`' % (
 
                    'msg': 'removed member `%s` from user group `%s`' % (
 
                                TEST_USER_ADMIN_LOGIN, gr_name
 
                            ),
 
                    'success': True}
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
        UsersGroupModel().delete(users_group=gr_name)
 
        UserGroupModel().delete(users_group=gr_name)
 
        Session().commit()
 

	
 
    @mock.patch.object(UsersGroupModel, 'remove_user_from_group', crash)
 
    @mock.patch.object(UserGroupModel, 'remove_user_from_group', crash)
 
    def test_api_remove_user_from_users_group_exception_occurred(self):
 
        gr_name = 'test_group_3'
 
        gr = UsersGroupModel().create(gr_name)
 
        UsersGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
 
        gr = UserGroupModel().create(gr_name)
 
        UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
 
        Session().commit()
 
        id_, params = _build_data(self.apikey, 'remove_user_from_users_group',
 
                                  usersgroupid=gr_name,
 
                                  userid=TEST_USER_ADMIN_LOGIN)
 
        response = api_call(self, params)
 

	
 
        expected = 'failed to remove member from users group `%s`' % gr_name
 
        expected = 'failed to remove member from user group `%s`' % gr_name
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
        UsersGroupModel().delete(users_group=gr_name)
 
        UserGroupModel().delete(users_group=gr_name)
 
        Session().commit()
 

	
 
    @parameterized.expand([('none', 'repository.none'),
 
                           ('read', 'repository.read'),
 
                           ('write', 'repository.write'),
 
                           ('admin', 'repository.admin')])
 
    def test_api_grant_user_permission(self, name, perm):
 
        id_, params = _build_data(self.apikey, 'grant_user_permission',
 
                                  repoid=self.REPO,
 
                                  userid=TEST_USER_ADMIN_LOGIN,
 
                                  perm=perm)
 
        response = api_call(self, params)
 
@@ -1215,80 +1215,80 @@ class BaseTestApi(object):
 
        expected = 'failed to edit permission for user: `%s` in repo: `%s`' % (
 
                    TEST_USER_ADMIN_LOGIN, self.REPO
 
                )
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    @parameterized.expand([('none', 'repository.none'),
 
                           ('read', 'repository.read'),
 
                           ('write', 'repository.write'),
 
                           ('admin', 'repository.admin')])
 
    def test_api_grant_users_group_permission(self, name, perm):
 
        id_, params = _build_data(self.apikey, 'grant_users_group_permission',
 
                                  repoid=self.REPO,
 
                                  usersgroupid=TEST_USERS_GROUP,
 
                                  usersgroupid=TEST_USER_GROUP,
 
                                  perm=perm)
 
        response = api_call(self, params)
 

	
 
        ret = {
 
            'msg': 'Granted perm: `%s` for users group: `%s` in repo: `%s`' % (
 
                perm, TEST_USERS_GROUP, self.REPO
 
            'msg': 'Granted perm: `%s` for user group: `%s` in repo: `%s`' % (
 
                perm, TEST_USER_GROUP, self.REPO
 
            ),
 
            'success': True
 
        }
 
        expected = ret
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
    def test_api_grant_users_group_permission_wrong_permission(self):
 
        perm = 'haha.no.permission'
 
        id_, params = _build_data(self.apikey, 'grant_users_group_permission',
 
                                  repoid=self.REPO,
 
                                  usersgroupid=TEST_USERS_GROUP,
 
                                  usersgroupid=TEST_USER_GROUP,
 
                                  perm=perm)
 
        response = api_call(self, params)
 

	
 
        expected = 'permission `%s` does not exist' % perm
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    @mock.patch.object(RepoModel, 'grant_users_group_permission', crash)
 
    def test_api_grant_users_group_permission_exception_when_adding(self):
 
        perm = 'repository.read'
 
        id_, params = _build_data(self.apikey, 'grant_users_group_permission',
 
                                  repoid=self.REPO,
 
                                  usersgroupid=TEST_USERS_GROUP,
 
                                  usersgroupid=TEST_USER_GROUP,
 
                                  perm=perm)
 
        response = api_call(self, params)
 

	
 
        expected = 'failed to edit permission for users group: `%s` in repo: `%s`' % (
 
                    TEST_USERS_GROUP, self.REPO
 
        expected = 'failed to edit permission for user group: `%s` in repo: `%s`' % (
 
                    TEST_USER_GROUP, self.REPO
 
                )
 
        self._compare_error(id_, expected, given=response.body)
 

	
 
    def test_api_revoke_users_group_permission(self):
 
        RepoModel().grant_users_group_permission(repo=self.REPO,
 
                                                 group_name=TEST_USERS_GROUP,
 
                                                 group_name=TEST_USER_GROUP,
 
                                                 perm='repository.read')
 
        Session().commit()
 
        id_, params = _build_data(self.apikey, 'revoke_users_group_permission',
 
                                  repoid=self.REPO,
 
                                  usersgroupid=TEST_USERS_GROUP,)
 
                                  usersgroupid=TEST_USER_GROUP,)
 
        response = api_call(self, params)
 

	
 
        expected = {
 
            'msg': 'Revoked perm for users group: `%s` in repo: `%s`' % (
 
                TEST_USERS_GROUP, self.REPO
 
            'msg': 'Revoked perm for user group: `%s` in repo: `%s`' % (
 
                TEST_USER_GROUP, self.REPO
 
            ),
 
            'success': True
 
        }
 
        self._compare_ok(id_, expected, given=response.body)
 

	
 
    @mock.patch.object(RepoModel, 'revoke_users_group_permission', crash)
 
    def test_api_revoke_users_group_permission_exception_when_adding(self):
 

	
 
        id_, params = _build_data(self.apikey, 'revoke_users_group_permission',
 
                                  repoid=self.REPO,
 
                                  usersgroupid=TEST_USERS_GROUP,)
 
                                  usersgroupid=TEST_USER_GROUP,)
 
        response = api_call(self, params)
 

	
 
        expected = 'failed to edit permission for users group: `%s` in repo: `%s`' % (
 
                    TEST_USERS_GROUP, self.REPO
 
        expected = 'failed to edit permission for user group: `%s` in repo: `%s`' % (
 
                    TEST_USER_GROUP, self.REPO
 
                )
 
        self._compare_error(id_, expected, given=response.body)
rhodecode/tests/functional/test_admin_users_groups.py
Show inline comments
 
from rhodecode.tests import *
 
from rhodecode.model.db import UsersGroup, UsersGroupToPerm, Permission
 
from rhodecode.model.db import UserGroup, UserGroupToPerm, Permission
 

	
 
TEST_USERS_GROUP = 'admins_test'
 
TEST_USER_GROUP = 'admins_test'
 

	
 

	
 
class TestAdminUsersGroupsController(TestController):
 

	
 
    def test_index(self):
 
        response = self.app.get(url('users_groups'))
 
        # Test response...
 

	
 
    def test_index_as_xml(self):
 
        response = self.app.get(url('formatted_users_groups', format='xml'))
 

	
 
    def test_create(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP
 
        users_group_name = TEST_USER_GROUP
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name': users_group_name,
 
                                  'active':True})
 
        response.follow()
 

	
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % TEST_USERS_GROUP)
 
                               'created user group %s' % TEST_USER_GROUP)
 

	
 
    def test_new(self):
 
        response = self.app.get(url('new_users_group'))
 

	
 
    def test_new_as_xml(self):
 
        response = self.app.get(url('formatted_new_users_group', format='xml'))
 

	
 
    def test_update(self):
 
        response = self.app.put(url('users_group', id=1))
 

	
 
    def test_update_browser_fakeout(self):
 
        response = self.app.post(url('users_group', id=1),
 
                                 params=dict(_method='put'))
 

	
 
    def test_delete(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP + 'another'
 
        users_group_name = TEST_USER_GROUP + 'another'
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name':users_group_name,
 
                                  'active':True})
 
        response.follow()
 

	
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % users_group_name)
 
                               'created user group %s' % users_group_name)
 

	
 
        gr = self.Session.query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
        gr = self.Session.query(UserGroup)\
 
                           .filter(UserGroup.users_group_name ==
 
                                   users_group_name).one()
 

	
 
        response = self.app.delete(url('users_group', id=gr.users_group_id))
 

	
 
        gr = self.Session.query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
        gr = self.Session.query(UserGroup)\
 
                           .filter(UserGroup.users_group_name ==
 
                                   users_group_name).scalar()
 

	
 
        self.assertEqual(gr, None)
 

	
 
    def test_enable_repository_read_on_group(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP + 'another2'
 
        users_group_name = TEST_USER_GROUP + 'another2'
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name': users_group_name,
 
                                  'active': True})
 
        response.follow()
 

	
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % users_group_name)
 
                               'created user group %s' % users_group_name)
 
        ## ENABLE REPO CREATE ON A GROUP
 
        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
 
                                 {'create_repo_perm': True})
 

	
 
        response.follow()
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        p = Permission.get_by_key('hg.create.repository')
 
        p2 = Permission.get_by_key('hg.fork.none')
 
        # check if user has this perms, they should be here since
 
        # defaults are on
 
        perms = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == ug).all()
 
        perms = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == ug).all()
 

	
 
        self.assertEqual(
 
            [[x.users_group_id, x.permission_id, ] for x in perms],
 
            [[ug.users_group_id, p.permission_id],
 
             [ug.users_group_id, p2.permission_id]]
 
        )
 

	
 
        ## DISABLE REPO CREATE ON A GROUP
 
        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
 
                                    {})
 

	
 
        response.follow()
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        p = Permission.get_by_key('hg.create.none')
 
        p2 = Permission.get_by_key('hg.fork.none')
 
        # check if user has this perms, they should be here since
 
        # defaults are on
 
        perms = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == ug).all()
 
        perms = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == ug).all()
 

	
 
        self.assertEqual(
 
            sorted([[x.users_group_id, x.permission_id, ] for x in perms]),
 
            sorted([[ug.users_group_id, p.permission_id],
 
             [ug.users_group_id, p2.permission_id]])
 
        )
 

	
 
        # DELETE !
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        ugid = ug.users_group_id
 
        response = self.app.delete(url('users_group', id=ug.users_group_id))
 
        response = response.follow()
 
        gr = self.Session.query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
        gr = self.Session.query(UserGroup)\
 
                           .filter(UserGroup.users_group_name ==
 
                                   users_group_name).scalar()
 

	
 
        self.assertEqual(gr, None)
 
        p = Permission.get_by_key('hg.create.repository')
 
        perms = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group_id == ugid).all()
 
        perms = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group_id == ugid).all()
 
        perms = [[x.users_group_id,
 
                  x.permission_id, ] for x in perms]
 
        self.assertEqual(
 
            perms,
 
            []
 
        )
 

	
 
    def test_enable_repository_fork_on_group(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP + 'another2'
 
        users_group_name = TEST_USER_GROUP + 'another2'
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name': users_group_name,
 
                                  'active': True})
 
        response.follow()
 

	
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % users_group_name)
 
                               'created user group %s' % users_group_name)
 
        ## ENABLE REPO CREATE ON A GROUP
 
        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
 
                                 {'fork_repo_perm': True})
 

	
 
        response.follow()
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        p = Permission.get_by_key('hg.create.none')
 
        p2 = Permission.get_by_key('hg.fork.repository')
 
        # check if user has this perms, they should be here since
 
        # defaults are on
 
        perms = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == ug).all()
 
        perms = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == ug).all()
 

	
 
        self.assertEqual(
 
            [[x.users_group_id, x.permission_id, ] for x in perms],
 
            [[ug.users_group_id, p.permission_id],
 
             [ug.users_group_id, p2.permission_id]]
 
        )
 

	
 
        ## DISABLE REPO CREATE ON A GROUP
 
        response = self.app.put(url('users_group_perm', id=ug.users_group_id),
 
                                    {})
 

	
 
        response.follow()
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        p = Permission.get_by_key('hg.create.none')
 
        p2 = Permission.get_by_key('hg.fork.none')
 
        # check if user has this perms, they should be here since
 
        # defaults are on
 
        perms = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group == ug).all()
 
        perms = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group == ug).all()
 

	
 
        self.assertEqual(
 
            [[x.users_group_id, x.permission_id, ] for x in perms],
 
            [[ug.users_group_id, p.permission_id],
 
             [ug.users_group_id, p2.permission_id]]
 
        )
 

	
 
        # DELETE !
 
        ug = UsersGroup.get_by_group_name(users_group_name)
 
        ug = UserGroup.get_by_group_name(users_group_name)
 
        ugid = ug.users_group_id
 
        response = self.app.delete(url('users_group', id=ug.users_group_id))
 
        response = response.follow()
 
        gr = self.Session.query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
        gr = self.Session.query(UserGroup)\
 
                           .filter(UserGroup.users_group_name ==
 
                                   users_group_name).scalar()
 

	
 
        self.assertEqual(gr, None)
 
        p = Permission.get_by_key('hg.fork.repository')
 
        perms = UsersGroupToPerm.query()\
 
            .filter(UsersGroupToPerm.users_group_id == ugid).all()
 
        perms = UserGroupToPerm.query()\
 
            .filter(UserGroupToPerm.users_group_id == ugid).all()
 
        perms = [[x.users_group_id,
 
                  x.permission_id, ] for x in perms]
 
        self.assertEqual(
 
            perms,
 
            []
 
        )
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('users_group', id=1),
 
                                 params=dict(_method='delete'))
 

	
 
    def test_show(self):
rhodecode/tests/functional/test_compare.py
Show inline comments
 
@@ -111,25 +111,25 @@ class TestCompareController(TestControll
 
        response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, rev2, repo2.repo_name, rev1))
 
        response.mustcontain("""Showing 2 commits""")
 
        response.mustcontain("""1 file changed with 2 insertions and 0 deletions""")
 

	
 
        response.mustcontain("""<div class="message tooltip" title="commit2" style="white-space:normal">commit2</div>""")
 
        response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
 

	
 
        response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
 
        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
 
        ## files
 
        response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s#C--826e8142e6ba">file1</a>""" % (repo1.repo_name, rev2, rev1, repo2.repo_name))
 
        #swap
 
        response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?as_form=None&amp;other_repo=%s">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 
        response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 

	
 
    def test_compare_forks_on_branch_extra_commits_origin_has_incomming_hg(self):
 
        self.log_user()
 

	
 
        repo1 = RepoModel().create_repo(repo_name='one', repo_type='hg',
 
                                        description='diff-test',
 
                                        owner=TEST_USER_ADMIN_LOGIN)
 
        Session().commit()
 
        self.r1_id = repo1.repo_id
 

	
 
        #commit something !
 
        cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
 
@@ -164,25 +164,25 @@ class TestCompareController(TestControll
 
        response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, rev2, repo2.repo_name, rev1))
 
        response.mustcontain("""Showing 2 commits""")
 
        response.mustcontain("""1 file changed with 2 insertions and 0 deletions""")
 

	
 
        response.mustcontain("""<div class="message tooltip" title="commit2" style="white-space:normal">commit2</div>""")
 
        response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
 

	
 
        response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
 
        response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
 
        ## files
 
        response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s#C--826e8142e6ba">file1</a>""" % (repo1.repo_name, rev2, rev1, repo2.repo_name))
 
        #swap
 
        response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?as_form=None&amp;other_repo=%s">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 
        response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 

	
 
    def test_compare_cherry_pick_changesets_from_bottom(self):
 

	
 
#        repo1:
 
#            cs0:
 
#            cs1:
 
#        repo1-fork- in which we will cherry pick bottom changesets
 
#            cs0:
 
#            cs1:
 
#            cs2: x
 
#            cs3: x
 
#            cs4: x
rhodecode/tests/functional/test_repos_groups.py
Show inline comments
 
from rhodecode.tests import *
 

	
 

	
 
class TestReposGroupsController(TestController):
 

	
 
    def test_index(self):
 
        self.log_user()
 
        response = self.app.get(url('repos_groups'))
 
        response.mustcontain('There are no repositories groups yet')
 
        response.mustcontain('There are no repository groups yet')
 

	
 
#    def test_index_as_xml(self):
 
#        response = self.app.get(url('formatted_repos_groups', format='xml'))
 
#
 
#    def test_create(self):
 
#        response = self.app.post(url('repos_groups'))
 

	
 
    def test_new(self):
 
        self.log_user()
 
        response = self.app.get(url('new_repos_group'))
 

	
 
    def test_new_by_regular_user(self):
rhodecode/tests/models/test_permissions.py
Show inline comments
 
import os
 
import unittest
 
from rhodecode.tests import *
 
from rhodecode.tests.models.common import _make_group
 
from rhodecode.model.repos_group import ReposGroupModel
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.db import RepoGroup, User, UsersGroupRepoGroupToPerm
 
from rhodecode.model.db import RepoGroup, User, UserGroupRepoGroupToPerm
 
from rhodecode.model.user import UserModel
 

	
 
from rhodecode.model.meta import Session
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 
from rhodecode.lib.auth import AuthUser
 
from rhodecode.tests.api.api_base import create_repo
 

	
 

	
 
class TestPermissions(unittest.TestCase):
 
    def __init__(self, methodName='runTest'):
 
        super(TestPermissions, self).__init__(methodName=methodName)
 

	
 
    def setUp(self):
 
        self.u1 = UserModel().create_or_update(
 
            username=u'u1', password=u'qweqwe',
 
            email=u'u1@rhodecode.org', firstname=u'u1', lastname=u'u1'
 
@@ -42,25 +42,25 @@ class TestPermissions(unittest.TestCase)
 
            RepoModel().delete(repo=self.test_repo)
 

	
 
        UserModel().delete(self.u1)
 
        UserModel().delete(self.u2)
 
        UserModel().delete(self.u3)
 
        UserModel().delete(self.a1)
 
        if hasattr(self, 'g1'):
 
            ReposGroupModel().delete(self.g1.group_id)
 
        if hasattr(self, 'g2'):
 
            ReposGroupModel().delete(self.g2.group_id)
 

	
 
        if hasattr(self, 'ug1'):
 
            UsersGroupModel().delete(self.ug1, force=True)
 
            UserGroupModel().delete(self.ug1, force=True)
 

	
 
        Session().commit()
 

	
 
    def test_default_perms_set(self):
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        perms = {
 
            'repositories_groups': {},
 
            'global': set([u'hg.create.repository', u'repository.read',
 
                           u'hg.register.manual_activate']),
 
            'repositories': {u'vcs_test_hg': u'repository.read'}
 
        }
 
        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
 
@@ -115,28 +115,28 @@ class TestPermissions(unittest.TestCase)
 
            'repositories_groups': {u'test1': 'group.admin', u'test2': 'group.admin'},
 
            'global': set(['hg.admin']),
 
            'repositories': {u'vcs_test_hg': 'repository.admin'}
 
        }
 

	
 
        self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
 
                         perms['repositories'][HG_REPO])
 
        self.assertEqual(a1_auth.permissions['repositories_groups'],
 
                         perms['repositories_groups'])
 

	
 
    def test_propagated_permission_from_users_group_by_explicit_perms_exist(self):
 
        # make group
 
        self.ug1 = UsersGroupModel().create('G1')
 
        self.ug1 = UserGroupModel().create('G1')
 
        # add user to group
 

	
 
        UsersGroupModel().add_user_to_group(self.ug1, self.u1)
 
        UserGroupModel().add_user_to_group(self.ug1, self.u1)
 

	
 
        # set permission to lower
 
        new_perm = 'repository.none'
 
        RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1, perm=new_perm)
 
        Session().commit()
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
 
                         new_perm)
 

	
 
        # grant perm for group this should not override permission from user
 
        # since it has explicitly set
 
        new_perm_gr = 'repository.write'
 
@@ -149,52 +149,52 @@ class TestPermissions(unittest.TestCase)
 
            'repositories_groups': {},
 
            'global': set([u'hg.create.repository', u'repository.read',
 
                           u'hg.register.manual_activate']),
 
            'repositories': {u'vcs_test_hg': u'repository.read'}
 
        }
 
        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
 
                         new_perm)
 
        self.assertEqual(u1_auth.permissions['repositories_groups'],
 
                         perms['repositories_groups'])
 

	
 
    def test_propagated_permission_from_users_group(self):
 
        # make group
 
        self.ug1 = UsersGroupModel().create('G1')
 
        self.ug1 = UserGroupModel().create('G1')
 
        # add user to group
 

	
 
        UsersGroupModel().add_user_to_group(self.ug1, self.u3)
 
        UserGroupModel().add_user_to_group(self.ug1, self.u3)
 

	
 
        # grant perm for group this should override default permission from user
 
        new_perm_gr = 'repository.write'
 
        RepoModel().grant_users_group_permission(repo=HG_REPO,
 
                                                 group_name=self.ug1,
 
                                                 perm=new_perm_gr)
 
        # check perms
 
        u3_auth = AuthUser(user_id=self.u3.user_id)
 
        perms = {
 
            'repositories_groups': {},
 
            'global': set([u'hg.create.repository', u'repository.read',
 
                           u'hg.register.manual_activate']),
 
            'repositories': {u'vcs_test_hg': u'repository.read'}
 
        }
 
        self.assertEqual(u3_auth.permissions['repositories'][HG_REPO],
 
                         new_perm_gr)
 
        self.assertEqual(u3_auth.permissions['repositories_groups'],
 
                         perms['repositories_groups'])
 

	
 
    def test_propagated_permission_from_users_group_lower_weight(self):
 
        # make group
 
        self.ug1 = UsersGroupModel().create('G1')
 
        self.ug1 = UserGroupModel().create('G1')
 
        # add user to group
 
        UsersGroupModel().add_user_to_group(self.ug1, self.u1)
 
        UserGroupModel().add_user_to_group(self.ug1, self.u1)
 

	
 
        # set permission to lower
 
        new_perm_h = 'repository.write'
 
        RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1,
 
                                          perm=new_perm_h)
 
        Session().commit()
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
 
                         new_perm_h)
 

	
 
        # grant perm for group this should NOT override permission from user
 
        # since it's lower than granted
 
@@ -290,52 +290,52 @@ class TestPermissions(unittest.TestCase)
 
        self.g1 = _make_group('group1', skip_if_exists=True)
 
        Session().commit()
 
        a1_auth = AuthUser(user_id=self.anon.user_id)
 

	
 
        self.assertEqual(a1_auth.permissions['repositories_groups'],
 
                         {u'group1': u'group.read'})
 

	
 
        # set default permission to none
 
        ReposGroupModel().grant_user_permission(repos_group=self.g1,
 
                                                user=self.anon,
 
                                                perm='group.none')
 
        # make group
 
        self.ug1 = UsersGroupModel().create('G1')
 
        self.ug1 = UserGroupModel().create('G1')
 
        # add user to group
 
        UsersGroupModel().add_user_to_group(self.ug1, self.u1)
 
        UserGroupModel().add_user_to_group(self.ug1, self.u1)
 
        Session().commit()
 

	
 
        # check if user is in the group
 
        membrs = [x.user_id for x in UsersGroupModel().get(self.ug1.users_group_id).members]
 
        membrs = [x.user_id for x in UserGroupModel().get(self.ug1.users_group_id).members]
 
        self.assertEqual(membrs, [self.u1.user_id])
 
        # add some user to that group
 

	
 
        # check his permissions
 
        a1_auth = AuthUser(user_id=self.anon.user_id)
 
        self.assertEqual(a1_auth.permissions['repositories_groups'],
 
                         {u'group1': u'group.none'})
 

	
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        self.assertEqual(u1_auth.permissions['repositories_groups'],
 
                         {u'group1': u'group.none'})
 

	
 
        # grant ug1 read permissions for
 
        ReposGroupModel().grant_users_group_permission(repos_group=self.g1,
 
                                                       group_name=self.ug1,
 
                                                       perm='group.read')
 
        Session().commit()
 
        # check if the
 
        obj = Session().query(UsersGroupRepoGroupToPerm)\
 
            .filter(UsersGroupRepoGroupToPerm.group == self.g1)\
 
            .filter(UsersGroupRepoGroupToPerm.users_group == self.ug1)\
 
        obj = Session().query(UserGroupRepoGroupToPerm)\
 
            .filter(UserGroupRepoGroupToPerm.group == self.g1)\
 
            .filter(UserGroupRepoGroupToPerm.users_group == self.ug1)\
 
            .scalar()
 
        self.assertEqual(obj.permission.permission_name, 'group.read')
 

	
 
        a1_auth = AuthUser(user_id=self.anon.user_id)
 

	
 
        self.assertEqual(a1_auth.permissions['repositories_groups'],
 
                         {u'group1': u'group.none'})
 

	
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        self.assertEqual(u1_auth.permissions['repositories_groups'],
 
                         {u'group1': u'group.read'})
 

	
 
@@ -430,28 +430,28 @@ class TestPermissions(unittest.TestCase)
 
    def test_owner_permissions_doesnot_get_overwritten_by_group(self):
 
        #create repo as USER,
 
        self.test_repo = repo = RepoModel().create_repo(repo_name='myownrepo',
 
                                repo_type='hg',
 
                                description='desc',
 
                                owner=self.u1)
 

	
 
        Session().commit()
 
        #he has permissions of admin as owner
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
 
                         'repository.admin')
 
        #set his permission as users group, he should still be admin
 
        self.ug1 = UsersGroupModel().create('G1')
 
        #set his permission as user group, he should still be admin
 
        self.ug1 = UserGroupModel().create('G1')
 
        # add user to group
 
        UsersGroupModel().add_user_to_group(self.ug1, self.u1)
 
        UserGroupModel().add_user_to_group(self.ug1, self.u1)
 
        RepoModel().grant_users_group_permission(repo, group_name=self.ug1,
 
                                                 perm='repository.none')
 

	
 
        Session().commit()
 
        u1_auth = AuthUser(user_id=self.u1.user_id)
 
        self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
 
                         'repository.admin')
 

	
 
    def test_owner_permissions_doesnot_get_overwritten_by_others(self):
 
        #create repo as USER,
 
        self.test_repo = repo = RepoModel().create_repo(repo_name='myownrepo',
 
                                repo_type='hg',
rhodecode/tests/models/test_users.py
Show inline comments
 
import unittest
 
from rhodecode.tests import *
 

	
 
from rhodecode.model.db import User, UsersGroup, UsersGroupMember, UserEmailMap,\
 
from rhodecode.model.db import User, UserGroup, UserGroupMember, UserEmailMap,\
 
    Permission
 
from rhodecode.model.user import UserModel
 

	
 
from rhodecode.model.meta import Session
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 

	
 

	
 
class TestUser(unittest.TestCase):
 
    def __init__(self, methodName='runTest'):
 
        Session.remove()
 
        super(TestUser, self).__init__(methodName=methodName)
 

	
 
    def test_create_and_remove(self):
 
        usr = UserModel().create_or_update(username=u'test_user',
 
                                           password=u'qweqwe',
 
                                     email=u'u232@rhodecode.org',
 
                                     firstname=u'u1', lastname=u'u1')
 
        Session().commit()
 
        self.assertEqual(User.get_by_username(u'test_user'), usr)
 

	
 
        # make users group
 
        users_group = UsersGroupModel().create('some_example_group')
 
        # make user group
 
        users_group = UserGroupModel().create('some_example_group')
 
        Session().commit()
 

	
 
        UsersGroupModel().add_user_to_group(users_group, usr)
 
        UserGroupModel().add_user_to_group(users_group, usr)
 
        Session().commit()
 

	
 
        self.assertEqual(UsersGroup.get(users_group.users_group_id), users_group)
 
        self.assertEqual(UsersGroupMember.query().count(), 1)
 
        self.assertEqual(UserGroup.get(users_group.users_group_id), users_group)
 
        self.assertEqual(UserGroupMember.query().count(), 1)
 
        UserModel().delete(usr.user_id)
 
        Session().commit()
 

	
 
        self.assertEqual(UsersGroupMember.query().all(), [])
 
        self.assertEqual(UserGroupMember.query().all(), [])
 

	
 
    def test_additonal_email_as_main(self):
 
        usr = UserModel().create_or_update(username=u'test_user',
 
                                           password=u'qweqwe',
 
                                     email=u'main_email@rhodecode.org',
 
                                     firstname=u'u1', lastname=u'u1')
 
        Session().commit()
 

	
 
        def do():
 
            m = UserEmailMap()
 
            m.email = u'main_email@rhodecode.org'
 
            m.user = usr
rhodecode/tests/models/test_users_group_permissions_on_groups.py
Show inline comments
 
import os
 
import unittest
 
import functools
 
from rhodecode.tests import *
 

	
 
from rhodecode.model.repos_group import ReposGroupModel
 
from rhodecode.model.db import RepoGroup, Repository, User
 

	
 
from rhodecode.model.meta import Session
 
from nose.tools import with_setup
 
from rhodecode.tests.models.common import _create_project_tree, check_tree_perms, \
 
    _get_perms, _check_expected_count, expected_count, _destroy_project_tree
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 
from rhodecode.model.repo import RepoModel
 

	
 

	
 
test_u2_id = None
 
test_u2_gr_id = None
 
_get_repo_perms = None
 
_get_group_perms = None
 

	
 

	
 
def permissions_setup_func(group_name='g0', perm='group.read', recursive=True):
 
    """
 
    Resets all permissions to perm attribute
 
@@ -31,28 +31,28 @@ def permissions_setup_func(group_name='g
 
    ReposGroupModel()._update_permissions(repos_group,
 
                                          perms_updates=perms_updates,
 
                                          recursive=recursive)
 
    Session().commit()
 

	
 

	
 
def setup_module():
 
    global test_u2_id, test_u2_gr_id, _get_repo_perms, _get_group_perms
 
    test_u2 = _create_project_tree()
 
    Session().commit()
 
    test_u2_id = test_u2.user_id
 

	
 
    gr1 = UsersGroupModel().create(name='perms_group_1')
 
    gr1 = UserGroupModel().create(name='perms_group_1')
 
    Session().commit()
 
    test_u2_gr_id = gr1.users_group_id
 
    UsersGroupModel().add_user_to_group(gr1, user=test_u2_id)
 
    UserGroupModel().add_user_to_group(gr1, user=test_u2_id)
 
    Session().commit()
 

	
 
    _get_repo_perms = functools.partial(_get_perms, key='repositories',
 
                                        test_u1_id=test_u2_id)
 
    _get_group_perms = functools.partial(_get_perms, key='repositories_groups',
 
                                         test_u1_id=test_u2_id)
 

	
 

	
 
def teardown_module():
 
    _destroy_project_tree(test_u2_id)
 

	
 

	
rhodecode/tests/test_libs.py
Show inline comments
 
@@ -200,55 +200,91 @@ class TestLibs(unittest.TestCase):
 
            fake = fake_conf(alternative_gravatar_url='http://test.com/{md5email}/{size}')
 
            with mock.patch('pylons.config', fake):
 
                em = 'test@foo.com'
 
                grav = gravatar_url(email_address=em, size=24)
 
                assert grav == 'http://test.com/%s/%s' % (_md5(em), 24)
 

	
 
            fake = fake_conf(alternative_gravatar_url='{scheme}://{netloc}/{md5email}/{size}')
 
            with mock.patch('pylons.config', fake):
 
                em = 'test@foo.com'
 
                grav = gravatar_url(email_address=em, size=24)
 
                assert grav == 'https://server.com/%s/%s' % (_md5(em), 24)
 

	
 
    def _quick_url(self, text, tmpl="""<a class="revision-link" href="%s">%s</a>""", url_=None):
 
        """
 
        Changes `some text url[foo]` => `some text <a href="/">foo</a>
 

	
 
        :param text:
 
        """
 
        import re
 
        #quickly change expected url[] into a link
 
        URL_PAT = re.compile(r'(?:url\[)(.+?)(?:\])')
 

	
 
        def url_func(match_obj):
 
            _url = match_obj.groups()[0]
 
            return tmpl % (url_ or '/some-url', _url)
 
        return URL_PAT.sub(url_func, text)
 

	
 
    @parameterized.expand([
 
      ("",
 
       ""),
 
      ("git-svn-id: https://svn.apache.org/repos/asf/libcloud/trunk@1441655 13f79535-47bb-0310-9956-ffa450edef68",
 
       "git-svn-id: https://svn.apache.org/repos/asf/libcloud/trunk@1441655 13f79535-47bb-0310-9956-ffa450edef68"),
 
      ("from rev 000000000000",
 
       "from rev url[000000000000]"),
 
      ("from rev 000000000000123123 also rev 000000000000",
 
       "from rev url[000000000000123123] also rev url[000000000000]"),
 
      ("this should-000 00",
 
       "this should-000 00"),
 
      ("longtextffffffffff rev 123123123123",
 
       "longtextffffffffff rev url[123123123123]"),
 
      ("rev ffffffffffffffffffffffffffffffffffffffffffffffffff",
 
       "rev ffffffffffffffffffffffffffffffffffffffffffffffffff"),
 
      ("ffffffffffff some text traalaa",
 
       "url[ffffffffffff] some text traalaa"),
 
       ("""Multi line
 
       123123123123
 
       some text 123123123123""",
 
       some text 123123123123
 
       sometimes !
 
       """,
 
       """Multi line
 
       url[123123123123]
 
       some text url[123123123123]""")
 
       some text url[123123123123]
 
       sometimes !
 
       """)
 
    ])
 
    def test_urlify_changesets(self, sample, expected):
 
        import re
 

	
 
        def fake_url(self, *args, **kwargs):
 
            return '/some-url'
 

	
 
        #quickly change expected url[] into a link
 
        URL_PAT = re.compile(r'(?:url\[)(.+?)(?:\])')
 

	
 
        def url_func(match_obj):
 
            _url = match_obj.groups()[0]
 
            tmpl = """<a class="revision-link" href="/some-url">%s</a>"""
 
            return tmpl % _url
 

	
 
        expected = URL_PAT.sub(url_func, expected)
 
        expected = self._quick_url(expected)
 

	
 
        with mock.patch('pylons.url', fake_url):
 
            from rhodecode.lib.helpers import urlify_changesets
 
            self.assertEqual(urlify_changesets(sample, 'repo_name'), expected)
 

	
 
    @parameterized.expand([
 
      ("",
 
       "",
 
       ""),
 
      ("https://svn.apache.org/repos",
 
       "url[https://svn.apache.org/repos]",
 
       "https://svn.apache.org/repos"),
 
      ("http://svn.apache.org/repos",
 
       "url[http://svn.apache.org/repos]",
 
       "http://svn.apache.org/repos"),
 
      ("from rev a also rev http://google.com",
 
       "from rev a also rev url[http://google.com]",
 
       "http://google.com"),
 
       ("""Multi line
 
       https://foo.bar.com
 
       some text lalala""",
 
       """Multi line
 
       url[https://foo.bar.com]
 
       some text lalala""",
 
       "https://foo.bar.com")
 
    ])
 
    def test_urlify_test(self, sample, expected, url_):
 
        from rhodecode.lib.helpers import urlify_text
 
        expected = self._quick_url(expected,
 
                                   tmpl="""<a href="%s">%s</a>""", url_=url_)
 
        self.assertEqual(urlify_text(sample), expected)
rhodecode/tests/test_validators.py
Show inline comments
 
# -*- coding: utf-8 -*-
 
import unittest
 
import formencode
 

	
 
from rhodecode.tests import *
 

	
 
from rhodecode.model import validators as v
 
from rhodecode.model.users_group import UsersGroupModel
 
from rhodecode.model.users_group import UserGroupModel
 

	
 
from rhodecode.model.meta import Session
 
from rhodecode.model.repos_group import ReposGroupModel
 
from rhodecode.config.routing import ADMIN_PREFIX
 
from rhodecode.model.db import ChangesetStatus, Repository
 
from rhodecode.model.changeset_status import ChangesetStatusModel
 
from rhodecode.model.comment import ChangesetCommentsModel
 

	
 

	
 
class TestReposGroups(unittest.TestCase):
 

	
 
    def setUp(self):
 
@@ -42,43 +42,43 @@ class TestReposGroups(unittest.TestCase)
 
        self.assertRaises(formencode.Invalid, validator.to_python,
 
                          TEST_USER_ADMIN_LOGIN)
 
        self.assertEqual('test', validator.to_python('test'))
 

	
 
        validator = v.ValidUsername(edit=True, old_data={'user_id': 1})
 

	
 
    def test_ValidRepoUser(self):
 
        validator = v.ValidRepoUser()
 
        self.assertRaises(formencode.Invalid, validator.to_python, 'nouser')
 
        self.assertEqual(TEST_USER_ADMIN_LOGIN,
 
                         validator.to_python(TEST_USER_ADMIN_LOGIN))
 

	
 
    def test_ValidUsersGroup(self):
 
        validator = v.ValidUsersGroup()
 
    def test_ValidUserGroup(self):
 
        validator = v.ValidUserGroup()
 
        self.assertRaises(formencode.Invalid, validator.to_python, 'default')
 
        self.assertRaises(formencode.Invalid, validator.to_python, '.,')
 

	
 
        gr = UsersGroupModel().create('test')
 
        gr2 = UsersGroupModel().create('tes2')
 
        gr = UserGroupModel().create('test')
 
        gr2 = UserGroupModel().create('tes2')
 
        Session.commit()
 
        self.assertRaises(formencode.Invalid, validator.to_python, 'test')
 
        assert gr.users_group_id != None
 
        validator = v.ValidUsersGroup(edit=True,
 
        validator = v.ValidUserGroup(edit=True,
 
                                    old_data={'users_group_id':
 
                                              gr2.users_group_id})
 

	
 
        self.assertRaises(formencode.Invalid, validator.to_python, 'test')
 
        self.assertRaises(formencode.Invalid, validator.to_python, 'TesT')
 
        self.assertRaises(formencode.Invalid, validator.to_python, 'TEST')
 
        UsersGroupModel().delete(gr)
 
        UsersGroupModel().delete(gr2)
 
        UserGroupModel().delete(gr)
 
        UserGroupModel().delete(gr2)
 
        Session.commit()
 

	
 
    def test_ValidReposGroup(self):
 
        validator = v.ValidReposGroup()
 
        model = ReposGroupModel()
 
        self.assertRaises(formencode.Invalid, validator.to_python,
 
                          {'group_name': HG_REPO, })
 
        gr = model.create(group_name='test_gr', group_description='desc',
 
                          parent=None,
 
                          just_db=True,
 
                          owner=TEST_USER_ADMIN_LOGIN)
 
        self.assertRaises(formencode.Invalid,
setup.py
Show inline comments
 
@@ -26,29 +26,30 @@ callback = lambda V: ('.'.join(map(str, 
 
__version__ = _get_meta_var('VERSION', _metadata, callback)
 
__license__ = _get_meta_var('__license__', _metadata)
 
__author__ = _get_meta_var('__author__', _metadata)
 
__url__ = _get_meta_var('__url__', _metadata)
 
# defines current platform
 
__platform__ = platform.system()
 

	
 
is_windows = __platform__ in _get_meta_var('PLATFORM_WIN', _metadata)
 

	
 
requirements = [
 
    "waitress==0.8.2",
 
    "webob==1.0.8",
 
    "webtest==1.4.3",
 
    "Pylons==1.0.0",
 
    "Beaker==1.6.4",
 
    "WebHelpers==1.3",
 
    "formencode==1.2.4",
 
    "SQLAlchemy==0.7.9",
 
    "SQLAlchemy==0.7.10",
 
    "Mako==0.7.3",
 
    "pygments>=1.5",
 
    "whoosh>=2.4.0,<2.5",
 
    "celery>=2.2.5,<2.3",
 
    "babel",
 
    "python-dateutil>=1.5.0,<2.0.0",
 
    "dulwich>=0.8.7,<0.9.0",
 
    "markdown==2.2.1",
 
    "docutils==0.8.1",
 
    "simplejson==2.5.2",
 
    "mock",
 
]
0 comments (0 inline, 0 general)