"""
Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
from __future__ import with_statement
from routes import Mapper
from rhodecode.lib.utils import check_repo_fast as cr
def make_map(config):
"""Create, configure and return the routes Mapper"""
routes_map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
routes_map.minimization = False
routes_map.explicit = False
def check_repo(environ, match_dict):
check for valid repository for proper 404 handling
:param environ:
:param match_dict:
repo_name = match_dict.get('repo_name')
return not cr(repo_name, config['base_path'])
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be resolved
routes_map.connect('/error/{action}', controller='error')
routes_map.connect('/error/{action}/{id}', controller='error')
#==========================================================================
# CUSTOM ROUTES HERE
#MAIN PAGE
routes_map.connect('home', '/', controller='home', action='index')
routes_map.connect('repo_switcher', '/repos', controller='home', action='repo_switcher')
routes_map.connect('bugtracker', "http://bitbucket.org/marcinkuzminski/rhodecode/issues", _static=True)
routes_map.connect('gpl_license', "http://www.gnu.org/licenses/gpl.html", _static=True)
routes_map.connect('rhodecode_official', "http://rhodecode.org", _static=True)
#ADMIN REPOSITORY REST ROUTES
with routes_map.submapper(path_prefix='/_admin', controller='admin/repos') as m:
m.connect("repos", "/repos",
action="create", conditions=dict(method=["POST"]))
action="index", conditions=dict(method=["GET"]))
m.connect("formatted_repos", "/repos.{format}",
action="index",
conditions=dict(method=["GET"]))
m.connect("new_repo", "/repos/new",
action="new", conditions=dict(method=["GET"]))
m.connect("formatted_new_repo", "/repos/new.{format}",
m.connect("/repos/{repo_name:.*}",
action="update", conditions=dict(method=["PUT"],
function=check_repo))
action="delete", conditions=dict(method=["DELETE"],
m.connect("edit_repo", "/repos/{repo_name:.*}/edit",
action="edit", conditions=dict(method=["GET"],
m.connect("formatted_edit_repo", "/repos/{repo_name:.*}.{format}/edit",
m.connect("repo", "/repos/{repo_name:.*}",
action="show", conditions=dict(method=["GET"],
m.connect("formatted_repo", "/repos/{repo_name:.*}.{format}",
#ajax delete repo perm user
m.connect('delete_repo_user', "/repos_delete_user/{repo_name:.*}",
action="delete_perm_user", conditions=dict(method=["DELETE"],
#ajax delete repo perm users_group
m.connect('delete_repo_users_group', "/repos_delete_users_group/{repo_name:.*}",
action="delete_perm_users_group", conditions=dict(method=["DELETE"],
#settings actions
m.connect('repo_stats', "/repos_stats/{repo_name:.*}",
action="repo_stats", conditions=dict(method=["DELETE"],
m.connect('repo_cache', "/repos_cache/{repo_name:.*}",
action="repo_cache", conditions=dict(method=["DELETE"],
m.connect('repo_public_journal', "/repos_public_journal/{repo_name:.*}",
action="repo_public_journal", conditions=dict(method=["PUT"],
m.connect('repo_pull', "/repo_pull/{repo_name:.*}",
action="repo_pull", conditions=dict(method=["PUT"],
#ADMIN REPOS GROUP REST ROUTES
routes_map.resource('repos_group', 'repos_groups', controller='admin/repos_groups', path_prefix='/_admin')
#ADMIN USER REST ROUTES
routes_map.resource('user', 'users', controller='admin/users', path_prefix='/_admin')
#ADMIN USERS REST ROUTES
routes_map.resource('users_group', 'users_groups', controller='admin/users_groups', path_prefix='/_admin')
#ADMIN GROUP REST ROUTES
routes_map.resource('group', 'groups', controller='admin/groups', path_prefix='/_admin')
#ADMIN PERMISSIONS REST ROUTES
routes_map.resource('permission', 'permissions', controller='admin/permissions', path_prefix='/_admin')
##ADMIN LDAP SETTINGS
routes_map.connect('ldap_settings', '/_admin/ldap', controller='admin/ldap_settings',
action='ldap_settings', conditions=dict(method=["POST"]))
routes_map.connect('ldap_home', '/_admin/ldap', controller='admin/ldap_settings',)
#ADMIN SETTINGS REST ROUTES
with routes_map.submapper(path_prefix='/_admin', controller='admin/settings') as m:
m.connect("admin_settings", "/settings",
m.connect("formatted_admin_settings", "/settings.{format}",
m.connect("admin_new_setting", "/settings/new",
m.connect("formatted_admin_new_setting", "/settings/new.{format}",
m.connect("/settings/{setting_id}",
action="update", conditions=dict(method=["PUT"]))
action="delete", conditions=dict(method=["DELETE"]))
m.connect("admin_edit_setting", "/settings/{setting_id}/edit",
action="edit", conditions=dict(method=["GET"]))
m.connect("formatted_admin_edit_setting", "/settings/{setting_id}.{format}/edit",
m.connect("admin_setting", "/settings/{setting_id}",
action="show", conditions=dict(method=["GET"]))
m.connect("formatted_admin_setting", "/settings/{setting_id}.{format}",
m.connect("admin_settings_my_account", "/my_account",
action="my_account", conditions=dict(method=["GET"]))
m.connect("admin_settings_my_account_update", "/my_account_update",
action="my_account_update", conditions=dict(method=["PUT"]))
m.connect("admin_settings_create_repository", "/create_repository",
action="create_repository", conditions=dict(method=["GET"]))
#ADMIN MAIN PAGES
with routes_map.submapper(path_prefix='/_admin', controller='admin/admin') as m:
m.connect('admin_home', '', action='index')#main page
m.connect('admin_add_repo', '/add_repo/{new_repo:[a-z0-9\. _-]*}',
action='add_repo')
#USER JOURNAL
routes_map.connect('journal', '/_admin/journal', controller='journal',)
routes_map.connect('public_journal', '/_admin/public_journal', controller='journal', action="public_journal")
routes_map.connect('public_journal_rss', '/_admin/public_journal_rss', controller='journal', action="public_journal_rss")
routes_map.connect('public_journal_atom', '/_admin/public_journal_atom', controller='journal', action="public_journal_atom")
routes_map.connect('toggle_following', '/_admin/toggle_following', controller='journal',
action='toggle_following', conditions=dict(method=["POST"]))
#SEARCH
routes_map.connect('search', '/_admin/search', controller='search',)
routes_map.connect('search_repo', '/_admin/search/{search_repo:.*}', controller='search')
#LOGIN/LOGOUT/REGISTER/SIGN IN
routes_map.connect('login_home', '/_admin/login', controller='login')
routes_map.connect('logout_home', '/_admin/logout', controller='login', action='logout')
routes_map.connect('register', '/_admin/register', controller='login', action='register')
routes_map.connect('reset_password', '/_admin/password_reset', controller='login', action='password_reset')
#FEEDS
routes_map.connect('rss_feed_home', '/{repo_name:.*}/feed/rss',
controller='feed', action='rss',
conditions=dict(function=check_repo))
routes_map.connect('atom_feed_home', '/{repo_name:.*}/feed/atom',
controller='feed', action='atom',
#REPOSITORY ROUTES
routes_map.connect('changeset_home', '/{repo_name:.*}/changeset/{revision}',
controller='changeset', revision='tip',
routes_map.connect('raw_changeset_home', '/{repo_name:.*}/raw-changeset/{revision}',
controller='changeset', action='raw_changeset', revision='tip',
routes_map.connect('summary_home', '/{repo_name:.*}',
controller='summary', conditions=dict(function=check_repo))
routes_map.connect('summary_home', '/{repo_name:.*}/summary',
routes_map.connect('shortlog_home', '/{repo_name:.*}/shortlog',
controller='shortlog', conditions=dict(function=check_repo))
routes_map.connect('branches_home', '/{repo_name:.*}/branches',
controller='branches', conditions=dict(function=check_repo))
routes_map.connect('tags_home', '/{repo_name:.*}/tags',
controller='tags', conditions=dict(function=check_repo))
routes_map.connect('changelog_home', '/{repo_name:.*}/changelog',
controller='changelog', conditions=dict(function=check_repo))
routes_map.connect('files_home', '/{repo_name:.*}/files/{revision}/{f_path:.*}',
controller='files', revision='tip', f_path='',
routes_map.connect('files_diff_home', '/{repo_name:.*}/diff/{f_path:.*}',
controller='files', action='diff', revision='tip', f_path='',
routes_map.connect('files_rawfile_home', '/{repo_name:.*}/rawfile/{revision}/{f_path:.*}',
controller='files', action='rawfile', revision='tip', f_path='',
routes_map.connect('files_raw_home', '/{repo_name:.*}/raw/{revision}/{f_path:.*}',
controller='files', action='raw', revision='tip', f_path='',
routes_map.connect('files_annotate_home', '/{repo_name:.*}/annotate/{revision}/{f_path:.*}',
controller='files', action='annotate', revision='tip', f_path='',
routes_map.connect('files_archive_home', '/{repo_name:.*}/archive/{fname}',
controller='files', action='archivefile',
routes_map.connect('repo_settings_delete', '/{repo_name:.*}/settings',
controller='settings', action="delete",
conditions=dict(method=["DELETE"], function=check_repo))
routes_map.connect('repo_settings_update', '/{repo_name:.*}/settings',
controller='settings', action="update",
conditions=dict(method=["PUT"], function=check_repo))
routes_map.connect('repo_settings_home', '/{repo_name:.*}/settings',
controller='settings', action='index',
routes_map.connect('repo_fork_create_home', '/{repo_name:.*}/fork',
controller='settings', action='fork_create',
conditions=dict(function=check_repo, method=["POST"]))
routes_map.connect('repo_fork_home', '/{repo_name:.*}/fork',
controller='settings', action='fork',
return routes_map
new file 100644
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from rhodecode.lib.base import BaseController, render
log = logging.getLogger(__name__)
class ReposGroupsController(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('repos_group', 'repos_groups')
def index(self, format='html'):
"""GET /repos_groups: All items in the collection"""
# url('repos_groups')
def create(self):
"""POST /repos_groups: Create a new item"""
def new(self, format='html'):
"""GET /repos_groups/new: Form to create a new item"""
# url('new_repos_group')
def update(self, id):
"""PUT /repos_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('repos_group', id=ID),
# method='put')
# url('repos_group', id=ID)
def delete(self, id):
"""DELETE /repos_groups/id: Delete an existing item"""
# <input type="hidden" name="_method" value="DELETE" />
# method='delete')
def show(self, id, format='html'):
"""GET /repos_groups/id: Show a specific item"""
def edit(self, id, format='html'):
"""GET /repos_groups/id/edit: Form to edit an existing item"""
# url('edit_repos_group', id=ID)
# -*- coding: utf-8 -*-
rhodecode.controllers.summary
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Summary controller for Rhodecode
:created_on: Apr 18, 2010
:author: marcink
:copyright: (C) 2009-2011 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; version 2
# of the License or (at your opinion) any later version of the license.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import calendar
from time import mktime
from datetime import datetime, timedelta, date
from vcs.exceptions import ChangesetError
from pylons import tmpl_context as c, request, url
from pylons.i18n.translation import _
from rhodecode.model.db import Statistics
from rhodecode.model.db import Statistics, Repository
from rhodecode.model.repo import RepoModel
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
from rhodecode.lib.base import BaseRepoController, render
from rhodecode.lib.utils import OrderedDict, EmptyChangeset
from rhodecode.lib.celerylib import run_task
from rhodecode.lib.celerylib.tasks import get_commits_stats
from rhodecode.lib.helpers import RepoPage
try:
import json
except ImportError:
#python 2.5 compatibility
import simplejson as json
class SummaryController(BaseRepoController):
@LoginRequired()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
def __before__(self):
super(SummaryController, self).__before__()
def index(self):
c.repo, dbrepo = self.scm_model.get(c.repo_name)
c.dbrepo = dbrepo
def index(self, repo_name):
e = request.environ
c.dbrepo = dbrepo = Repository.by_repo_name(repo_name)
c.following = self.scm_model.is_following_repo(c.repo_name,
self.rhodecode_user.user_id)
c.following = self.scm_model.is_following_repo(repo_name,
def url_generator(**kw):
return url('shortlog_home', repo_name=c.repo_name, **kw)
return url('shortlog_home', repo_name=repo_name, **kw)
c.repo_changesets = RepoPage(c.repo, page=1, items_per_page=10,
c.repo_changesets = RepoPage(c.rhodecode_repo, page=1, items_per_page=10,
url=url_generator)
if self.rhodecode_user.username == 'default':
#for default(anonymous) user we don't need to pass credentials
username = ''
password = ''
else:
username = str(self.rhodecode_user.username)
password = '@'
uri = u'%(protocol)s://%(user)s%(password)s%(host)s%(prefix)s/%(repo_name)s' % {
'protocol': e.get('wsgi.url_scheme'),
'user':username,
'password':password,
'host':e.get('HTTP_HOST'),
'prefix':e.get('SCRIPT_NAME'),
'repo_name':c.repo_name, }
'repo_name':repo_name, }
c.clone_repo_url = uri
c.repo_tags = OrderedDict()
for name, hash in c.repo.tags.items()[:10]:
for name, hash in c.rhodecode_repo.tags.items()[:10]:
c.repo_tags[name] = c.repo.get_changeset(hash)
c.repo_tags[name] = c.rhodecode_repo.get_changeset(hash)
except ChangesetError:
c.repo_tags[name] = EmptyChangeset(hash)
c.repo_branches = OrderedDict()
for name, hash in c.repo.branches.items()[:10]:
for name, hash in c.rhodecode_repo.branches.items()[:10]:
c.repo_branches[name] = c.repo.get_changeset(hash)
c.repo_branches[name] = c.rhodecode_repo.get_changeset(hash)
c.repo_branches[name] = EmptyChangeset(hash)
td = date.today() + timedelta(days=1)
td_1m = td - timedelta(days=calendar.mdays[td.month])
td_1y = td - timedelta(days=365)
ts_min_m = mktime(td_1m.timetuple())
ts_min_y = mktime(td_1y.timetuple())
ts_max_y = mktime(td.timetuple())
if dbrepo.enable_statistics:
c.no_data_msg = _('No data loaded yet')
run_task(get_commits_stats, c.repo.name, ts_min_y, ts_max_y)
run_task(get_commits_stats, c.dbrepo.repo_name, ts_min_y, ts_max_y)
c.no_data_msg = _('Statistics are disabled for this repository')
c.ts_min = ts_min_m
c.ts_max = ts_max_y
stats = self.sa.query(Statistics)\
.filter(Statistics.repository == dbrepo)\
.scalar()
if stats and stats.languages:
c.no_data = False is dbrepo.enable_statistics
lang_stats = json.loads(stats.languages)
c.commit_data = stats.commit_activity
c.overview_data = stats.commit_activity_combined
c.trending_languages = json.dumps(OrderedDict(
sorted(lang_stats.items(), reverse=True,
key=lambda k: k[1])[:10]
)
c.commit_data = json.dumps({})
c.overview_data = json.dumps([[ts_min_y, 0], [ts_max_y, 10] ])
c.trending_languages = json.dumps({})
c.no_data = True
c.enable_downloads = dbrepo.enable_downloads
if c.enable_downloads:
c.download_options = self._get_download_links(c.repo)
c.download_options = self._get_download_links(c.rhodecode_repo)
return render('summary/summary.html')
def _get_download_links(self, repo):
download_l = []
branches_group = ([], _("Branches"))
tags_group = ([], _("Tags"))
for name, chs in c.rhodecode_repo.branches.items():
#chs = chs.split(':')[-1]
branches_group[0].append((chs, name),)
download_l.append(branches_group)
for name, chs in c.rhodecode_repo.tags.items():
tags_group[0].append((chs, name),)
download_l.append(tags_group)
return download_l
@@ -104,594 +104,597 @@ class _ToolTip(object):
function toolTipsId(){
var ids = [];
var tts = YAHOO.util.Dom.getElementsByClassName('tooltip');
for (var i = 0; i < tts.length; i++) {
//if element doesn't not have and id autogenerate one for tooltip
if (!tts[i].id){
tts[i].id='tt'+i*100;
}
ids.push(tts[i].id);
return ids
};
var myToolTips = new YAHOO.widget.Tooltip("tooltip", {
context: toolTipsId(),
monitorresize:false,
xyoffset :[0,0],
autodismissdelay:300000,
hidedelay:5,
showdelay:20,
});
// Set the text for the tooltip just before we display it. Lazy method
myToolTips.contextTriggerEvent.subscribe(
function(type, args) {
var context = args[0];
//positioning of tooltip
var tt_w = this.element.clientWidth;//tooltip width
var tt_h = this.element.clientHeight;//tooltip height
var context_w = context.offsetWidth;
var context_h = context.offsetHeight;
var pos_x = YAHOO.util.Dom.getX(context);
var pos_y = YAHOO.util.Dom.getY(context);
var display_strategy = 'right';
var xy_pos = [0,0];
switch (display_strategy){
case 'top':
var cur_x = (pos_x+context_w/2)-(tt_w/2);
var cur_y = (pos_y-tt_h-4);
xy_pos = [cur_x,cur_y];
break;
case 'bottom':
var cur_y = pos_y+context_h+4;
case 'left':
var cur_x = (pos_x-tt_w-4);
var cur_y = pos_y-((tt_h/2)-context_h/2);
case 'right':
var cur_x = (pos_x+context_w+4);
default:
var cur_y = pos_y-tt_h-4;
this.cfg.setProperty("xy",xy_pos);
//Mouse out
myToolTips.contextMouseOutEvent.subscribe(
'''
return literal(js)
tooltip = _ToolTip()
class _FilesBreadCrumbs(object):
def __call__(self, repo_name, rev, paths):
if isinstance(paths, str):
paths = paths.decode('utf-8', 'replace')
url_l = [link_to(repo_name, url('files_home',
repo_name=repo_name,
revision=rev, f_path=''))]
paths_l = paths.split('/')
for cnt, p in enumerate(paths_l):
if p != '':
url_l.append(link_to(p, url('files_home',
revision=rev,
f_path='/'.join(paths_l[:cnt + 1]))))
return literal('/'.join(url_l))
files_breadcrumbs = _FilesBreadCrumbs()
class CodeHtmlFormatter(HtmlFormatter):
"""My code Html Formatter for source codes
def wrap(self, source, outfile):
return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
def _wrap_code(self, source):
for cnt, it in enumerate(source):
i, t = it
t = '<div id="L%s">%s</div>' % (cnt + 1, t)
yield i, t
def _wrap_tablelinenos(self, inner):
dummyoutfile = StringIO.StringIO()
lncount = 0
for t, line in inner:
if t:
lncount += 1
dummyoutfile.write(line)
fl = self.linenostart
mw = len(str(lncount + fl - 1))
sp = self.linenospecial
st = self.linenostep
la = self.lineanchors
aln = self.anchorlinenos
nocls = self.noclasses
if sp:
lines = []
for i in range(fl, fl + lncount):
if i % st == 0:
if i % sp == 0:
if aln:
lines.append('<a href="#%s%d" class="special">%*d</a>' %
(la, i, mw, i))
lines.append('<span class="special">%*d</span>' % (mw, i))
lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
lines.append('%*d' % (mw, i))
lines.append('')
ls = '\n'.join(lines)
# in case you wonder about the seemingly redundant <div> here: since the
# content in the other cell also is wrapped in a div, some browsers in
# some configurations seem to mess up the formatting...
if nocls:
yield 0, ('<table class="%stable">' % self.cssclass +
'<tr><td><div class="linenodiv" '
'style="background-color: #f0f0f0; padding-right: 10px">'
'<pre style="line-height: 125%">' +
ls + '</pre></div></td><td class="code">')
'<tr><td class="linenos"><div class="linenodiv"><pre>' +
yield 0, dummyoutfile.getvalue()
yield 0, '</td></tr></table>'
def pygmentize(filenode, **kwargs):
"""pygmentize function using pygments
:param filenode:
return literal(code_highlight(filenode.content,
filenode.lexer, CodeHtmlFormatter(**kwargs)))
def pygmentize_annotation(filenode, **kwargs):
def pygmentize_annotation(repo_name, filenode, **kwargs):
"""pygmentize function for annotation
color_dict = {}
def gen_color(n=10000):
"""generator for getting n of evenly distributed colors using
hsv color and golden ratio. It always return same order of colors
:returns: RGB tuple
import colorsys
golden_ratio = 0.618033988749895
h = 0.22717784590367374
for c in xrange(n):
h += golden_ratio
h %= 1
HSV_tuple = [h, 0.95, 0.95]
RGB_tuple = colorsys.hsv_to_rgb(*HSV_tuple)
yield map(lambda x:str(int(x * 256)), RGB_tuple)
cgenerator = gen_color()
def get_color_string(cs):
if color_dict.has_key(cs):
col = color_dict[cs]
col = color_dict[cs] = cgenerator.next()
return "color: rgb(%s)! important;" % (', '.join(col))
def url_func(changeset):
tooltip_html = "<div style='font-size:0.8em'><b>Author:</b>" + \
" %s<br/><b>Date:</b> %s</b><br/><b>Message:</b> %s<br/></div>"
def url_func(repo_name):
def _url_func(changeset):
tooltip_html = tooltip_html % (changeset.author,
changeset.date,
tooltip(changeset.message))
lnk_format = '%5s:%s' % ('r%s' % changeset.revision,
short_id(changeset.raw_id))
uri = link_to(
lnk_format,
url('changeset_home', repo_name=changeset.repository.name,
revision=changeset.raw_id),
style=get_color_string(changeset.raw_id),
class_='tooltip',
title=tooltip_html
url('changeset_home', repo_name=repo_name,
uri += '\n'
return uri
return literal(annotate_highlight(filenode, url_func, **kwargs))
return _url_func
return literal(annotate_highlight(filenode, url_func(repo_name), **kwargs))
def get_changeset_safe(repo, rev):
from vcs.backends.base import BaseRepository
from vcs.exceptions import RepositoryError
if not isinstance(repo, BaseRepository):
raise Exception('You must pass an Repository '
'object as first argument got %s', type(repo))
cs = repo.get_changeset(rev)
except RepositoryError:
from rhodecode.lib.utils import EmptyChangeset
cs = EmptyChangeset()
return cs
def is_following_repo(repo_name, user_id):
from rhodecode.model.scm import ScmModel
return ScmModel().is_following_repo(repo_name, user_id)
flash = _Flash()
#==============================================================================
# MERCURIAL FILTERS available via h.
from mercurial import util
from mercurial.templatefilters import person as _person
def _age(curdate):
"""turns a datetime into an age string."""
if not curdate:
return ''
agescales = [("year", 3600 * 24 * 365),
("month", 3600 * 24 * 30),
("day", 3600 * 24),
("hour", 3600),
("minute", 60),
("second", 1), ]
age = datetime.now() - curdate
age_seconds = (age.days * agescales[2][1]) + age.seconds
pos = 1
for scale in agescales:
if scale[1] <= age_seconds:
if pos == 6:pos = 5
return time_ago_in_words(curdate, agescales[pos][0]) + ' ' + _('ago')
pos += 1
return _('just now')
age = lambda x:_age(x)
capitalize = lambda x: x.capitalize()
email = util.email
email_or_none = lambda x: util.email(x) if util.email(x) != x else None
person = lambda x: _person(x)
short_id = lambda x: x[:12]
def bool2icon(value):
"""Returns True/False values represented as small html image of true/false
icons
:param value: bool value
if value is True:
return HTML.tag('img', src=url("/images/icons/accept.png"),
alt=_('True'))
if value is False:
return HTML.tag('img', src=url("/images/icons/cancel.png"),
alt=_('False'))
return value
def action_parser(user_log, feed=False):
"""This helper will action_map the specified string action into translated
fancy names with icons and links
:param user_log: user log instance
:param feed: use output for feeds (no html and fancy icons)
action = user_log.action
action_params = ' '
x = action.split(':')
if len(x) > 1:
action, action_params = x
def get_cs_links():
revs_limit = 5 #display this amount always
revs_top_limit = 50 #show upto this amount of changesets hidden
revs = action_params.split(',')
repo_name = user_log.repository.repo_name
repo, dbrepo = ScmModel().get(repo_name, retval='repo',
invalidation_list=[])
message = lambda rev: get_changeset_safe(repo, rev).message
cs_links = " " + ', '.join ([link_to(rev,
url('changeset_home',
revision=rev), title=tooltip(message(rev)),
class_='tooltip') for rev in revs[:revs_limit] ])
compare_view = (' <div class="compare_view tooltip" title="%s">'
'<a href="%s">%s</a> '
'</div>' % (_('Show all combined changesets %s->%s' \
% (revs[0], revs[-1])),
revision='%s...%s' % (revs[0], revs[-1])
),
_('compare view'))
if len(revs) > revs_limit:
uniq_id = revs[0]
html_tmpl = ('<span> %s '
'<a class="show_more" id="_%s" href="#more">%s</a> '
'%s</span>')
if not feed:
cs_links += html_tmpl % (_('and'), uniq_id, _('%s more') \
% (len(revs) - revs_limit),
_('revisions'))
html_tmpl = '<span id="%s" style="display:none"> %s </span>'
html_tmpl = '<span id="%s"> %s </span>'
cs_links += html_tmpl % (uniq_id, ', '.join([link_to(rev,
repo_name=repo_name, revision=rev),
title=message(rev), class_='tooltip')
for rev in revs[revs_limit:revs_top_limit]]))
if len(revs) > 1:
cs_links += compare_view
return cs_links
def get_fork_name():
repo_name = action_params
return _('fork name ') + str(link_to(action_params, url('summary_home',
repo_name=repo_name,)))
action_map = {'user_deleted_repo':(_('[deleted] repository'), None),
'user_created_repo':(_('[created] repository'), None),
'user_forked_repo':(_('[forked] repository'), get_fork_name),
'user_updated_repo':(_('[updated] repository'), None),
'admin_deleted_repo':(_('[delete] repository'), None),
'admin_created_repo':(_('[created] repository'), None),
'admin_forked_repo':(_('[forked] repository'), None),
'admin_updated_repo':(_('[updated] repository'), None),
'push':(_('[pushed] into'), get_cs_links),
'push_remote':(_('[pulled from remote] into'), get_cs_links),
'pull':(_('[pulled] from'), None),
'started_following_repo':(_('[started following] repository'), None),
'stopped_following_repo':(_('[stopped following] repository'), None),
action_str = action_map.get(action, action)
if feed:
action = action_str[0].replace('[', '').replace(']', '')
action = action_str[0].replace('[', '<span class="journal_highlight">')\
.replace(']', '</span>')
action_params_func = lambda :""
if callable(action_str[1]):
action_params_func = action_str[1]
return [literal(action), action_params_func]
def action_parser_icon(user_log):
action_params = None
tmpl = """<img src="%s%s" alt="%s"/>"""
map = {'user_deleted_repo':'database_delete.png',
'user_created_repo':'database_add.png',
'user_forked_repo':'arrow_divide.png',
'user_updated_repo':'database_edit.png',
'admin_deleted_repo':'database_delete.png',
'admin_created_repo':'database_add.png',
'admin_forked_repo':'arrow_divide.png',
'admin_updated_repo':'database_edit.png',
'push':'script_add.png',
'push_remote':'connect.png',
'pull':'down_16.png',
'started_following_repo':'heart_add.png',
'stopped_following_repo':'heart_delete.png',
return literal(tmpl % ((url('/images/icons/')),
map.get(action, action), action))
# PERMS
from rhodecode.lib.auth import HasPermissionAny, HasPermissionAll, \
HasRepoPermissionAny, HasRepoPermissionAll
# GRAVATAR URL
def gravatar_url(email_address, size=30):
if not str2bool(config['app_conf'].get('use_gravatar')):
return "/images/user%s.png" % size
ssl_enabled = 'https' == request.environ.get('wsgi.url_scheme')
default = 'identicon'
baseurl_nossl = "http://www.gravatar.com/avatar/"
baseurl_ssl = "https://secure.gravatar.com/avatar/"
baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl
if isinstance(email_address, unicode):
#hashlib crashes on unicode items
email_address = email_address.encode('utf8', 'replace')
# construct the url
gravatar_url = baseurl + hashlib.md5(email_address.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d':default, 's':str(size)})
return gravatar_url
# REPO PAGER
class RepoPage(Page):
def __init__(self, collection, page=1, items_per_page=20,
item_count=None, url=None, branch_name=None, **kwargs):
"""Create a "RepoPage" instance. special pager for paging
repository
self._url_generator = url
# Safe the kwargs class-wide so they can be used in the pager() method
self.kwargs = kwargs
# Save a reference to the collection
self.original_collection = collection
self.collection = collection
# The self.page is the number of the current page.
# The first page has the number 1!
self.page = int(page) # make it int() if we get it as a string
except (ValueError, TypeError):
self.page = 1
self.items_per_page = items_per_page
# Unless the user tells us how many items the collections has
# we calculate that ourselves.
if item_count is not None:
self.item_count = item_count
self.item_count = len(self.collection)
# Compute the number of the first and last available page
if self.item_count > 0:
self.first_page = 1
self.page_count = ((self.item_count - 1) / self.items_per_page) + 1
self.last_page = self.first_page + self.page_count - 1
# Make sure that the requested page number is the range of valid pages
if self.page > self.last_page:
self.page = self.last_page
elif self.page < self.first_page:
self.page = self.first_page
# Note: the number of items on this page can be less than
# items_per_page if the last page is not full
self.first_item = max(0, (self.item_count) - (self.page * items_per_page))
self.last_item = ((self.item_count - 1) - items_per_page * (self.page - 1))
iterator = self.collection.get_changesets(start=self.first_item,
end=self.last_item,
reverse=True,
branch_name=branch_name)
self.items = list(iterator)
# Links to previous and next page
if self.page > self.first_page:
self.previous_page = self.page - 1
self.previous_page = None
if self.page < self.last_page:
self.next_page = self.page + 1
self.next_page = None
# No items available
self.first_page = None
self.page_count = 0
self.last_page = None
self.first_item = None
self.last_item = None
self.items = []
# This is a subclass of the 'list' type. Initialise the list now.
list.__init__(self, self.items)
def changed_tooltip(nodes):
if nodes:
pref = ': <br/> '
suf = ''
if len(nodes) > 30:
suf = '<br/>' + _(' and %s more') % (len(nodes) - 30)
return literal(pref + '<br/> '.join([x.path.decode('utf-8', 'replace') for x in nodes[:30]]) + suf)
return ': ' + _('No Files')
def repo_link(groups_and_repos):
groups, repo_name = groups_and_repos
if not groups:
return repo_name
def make_link(group):
return link_to(group.group_name, url('/', group.group_id))
return link_to(group.group_name, url('repos_group', id=group.group_id))
return literal(' » '.join(map(make_link, groups)) + \
" » " + repo_name)
rhodecode.lib.indexers.daemon
A deamon will read from task table and run tasks
:created_on: Jan 26, 2010
import os
import sys
import traceback
from shutil import rmtree
from os.path import dirname as dn
from os.path import join as jn
#to get the rhodecode import
project_path = dn(dn(dn(dn(os.path.realpath(__file__)))))
sys.path.append(project_path)
from rhodecode.lib import safe_unicode
from rhodecode.lib.indexers import INDEX_EXTENSIONS, SCHEMA, IDX_NAME
from vcs.exceptions import ChangesetError, RepositoryError
from whoosh.index import create_in, open_dir
log = logging.getLogger('whooshIndexer')
# create logger
log.setLevel(logging.DEBUG)
log.propagate = False
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
log.addHandler(ch)
class WhooshIndexingDaemon(object):
Deamon for atomic jobs
def __init__(self, indexname='HG_INDEX', index_location=None,
repo_location=None, sa=None, repo_list=None):
self.indexname = indexname
self.index_location = index_location
if not index_location:
raise Exception('You have to provide index location')
self.repo_location = repo_location
if not repo_location:
raise Exception('You have to provide repositories location')
self.repo_paths = ScmModel(sa).repo_scan(self.repo_location)
if repo_list:
filtered_repo_paths = {}
for repo_name, repo in self.repo_paths.items():
if repo_name in repo_list:
filtered_repo_paths[repo.name] = repo
filtered_repo_paths[repo_name] = repo
self.repo_paths = filtered_repo_paths
self.initial = False
if not os.path.isdir(self.index_location):
os.makedirs(self.index_location)
log.info('Cannot run incremental index since it does not'
' yet exist running full build')
self.initial = True
def get_paths(self, repo):
"""recursive walk in root dir and return a set of all path in that dir
based on repository walk function
index_paths_ = set()
tip = repo.get_changeset('tip')
for topnode, dirs, files in tip.walk('/'):
for f in files:
index_paths_.add(jn(repo.path, f.path))
for dir in dirs:
except RepositoryError, e:
log.debug(traceback.format_exc())
pass
return index_paths_
def get_node(self, repo, path):
n_path = path[len(repo.path) + 1:]
node = repo.get_changeset().get_node(n_path)
return node
def get_node_mtime(self, node):
return mktime(node.last_changeset.date.timetuple())
def add_doc(self, writer, path, repo):
def add_doc(self, writer, path, repo, repo_name):
"""Adding doc to writer this function itself fetches data from
the instance of vcs backend"""
node = self.get_node(repo, path)
#we just index the content of chosen files, and skip binary files
if node.extension in INDEX_EXTENSIONS and not node.is_binary:
u_content = node.content
if not isinstance(u_content, unicode):
log.warning(' >> %s Could not get this content as unicode '
'replacing with empty content', path)
u_content = u''
log.debug(' >> %s [WITH CONTENT]' % path)
log.debug(' >> %s' % path)
#just index file name without it's content
writer.add_document(owner=unicode(repo.contact),
repository=safe_unicode(repo.name),
repository=safe_unicode(repo_name),
path=safe_unicode(path),
content=u_content,
modtime=self.get_node_mtime(node),
extension=node.extension)
def build_index(self):
if os.path.exists(self.index_location):
log.debug('removing previous index')
rmtree(self.index_location)
if not os.path.exists(self.index_location):
os.mkdir(self.index_location)
idx = create_in(self.index_location, SCHEMA, indexname=IDX_NAME)
writer = idx.writer()
for repo in self.repo_paths.values():
log.debug('building index @ %s' % repo.path)
for idx_path in self.get_paths(repo):
self.add_doc(writer, idx_path, repo)
self.add_doc(writer, idx_path, repo, repo_name)
log.debug('>> COMMITING CHANGES <<')
writer.commit(merge=True)
log.debug('>>> FINISHED BUILDING INDEX <<<')
def update_index(self):
log.debug('STARTING INCREMENTAL INDEXING UPDATE')
idx = open_dir(self.index_location, indexname=self.indexname)
# The set of all paths in the index
indexed_paths = set()
# The set of all paths we need to re-index
to_index = set()
reader = idx.reader()
# Loop over the stored fields in the index
for fields in reader.all_stored_fields():
indexed_path = fields['path']
indexed_paths.add(indexed_path)
repo = self.repo_paths[fields['repository']]
node = self.get_node(repo, indexed_path)
# This file was deleted since it was indexed
log.debug('removing from index %s' % indexed_path)
writer.delete_by_term('path', indexed_path)
# Check if this file was changed since it was indexed
indexed_time = fields['modtime']
mtime = self.get_node_mtime(node)
if mtime > indexed_time:
# The file has changed, delete it and add it to the list of
# files to reindex
log.debug('adding to reindex list %s' % indexed_path)
to_index.add(indexed_path)
# Loop over the files in the filesystem
# Assume we have a function that gathers the filenames of the
# documents to be indexed
for path in self.get_paths(repo):
if path in to_index or path not in indexed_paths:
# This is either a file that's changed, or a new file
# that wasn't indexed before. So index it!
self.add_doc(writer, path, repo)
self.add_doc(writer, path, repo, repo_name)
log.debug('re indexing %s' % path)
log.debug('>>> FINISHED REBUILDING INDEX <<<')
def run(self, full_index=False):
"""Run daemon"""
if full_index or self.initial:
self.build_index()
self.update_index()
## -*- coding: utf-8 -*-
<%inherit file="/base/base.html"/>
<%def name="title()">
${_('My account')} ${c.rhodecode_user.username} - ${c.rhodecode_name}
</%def>
<%def name="breadcrumbs_links()">
${_('My Account')}
<%def name="page_nav()">
${self.menu('admin')}
<%def name="main()">
<div class="box box-left">
<!-- box / title -->
<div class="title">
${self.breadcrumbs()}
</div>
<!-- end box / title -->
<div>
${h.form(url('admin_settings_my_account_update'),method='put')}
<div class="form">
<div class="field">
<div class="gravatar_box">
<div class="gravatar"><img alt="gravatar" src="${h.gravatar_url(c.user.email)}"/></div>
<p>
<strong>Change your avatar at <a href="http://gravatar.com">gravatar.com</a></strong><br/>
${_('Using')} ${c.user.email}
</p>
<div class="label">
<label>${_('API key')}</label> ${c.user.api_key}
<div class="fields">
<label for="username">${_('Username')}:</label>
<div class="input">
${h.text('username',class_="medium")}
<label for="new_password">${_('New password')}:</label>
${h.password('new_password',class_="medium")}
<label for="name">${_('First Name')}:</label>
${h.text('name',class_="medium")}
<label for="lastname">${_('Last Name')}:</label>
${h.text('lastname',class_="medium")}
<label for="email">${_('Email')}:</label>
${h.text('email',class_="medium")}
<div class="buttons">
${h.submit('save','Save',class_="ui-button")}
${h.reset('reset','Reset',class_="ui-button")}
${h.end_form()}
<div class="box box-right">
<h5>${_('My repositories')}
<input class="top-right-rounded-corner top-left-rounded-corner bottom-left-rounded-corner bottom-right-rounded-corner" id="q_filter" size="15" type="text" name="filter" value="${_('quick filter...')}"/>
</h5>
%if h.HasPermissionAny('hg.admin','hg.create.repository')():
<ul class="links">
<li>
<span>${h.link_to(_('ADD REPOSITORY'),h.url('admin_settings_create_repository'))}</span>
</li>
</ul>
%endif
<div class="table">
<table>
<thead>
<tr>
<th class="left">${_('Name')}</th>
<th class="left">${_('revision')}</th>
<th colspan="2" class="left">${_('action')}</th>
</thead>
<tbody>
%if c.user_repos:
%for repo in c.user_repos:
<td>
%if repo['dbrepo']['repo_type'] =='hg':
<img class="icon" title="${_('Mercurial repository')}" alt="${_('Mercurial repository')}" src="${h.url("/images/icons/hgicon.png")}"/>
%elif repo['dbrepo']['repo_type'] =='git':
<img class="icon" title="${_('Git repository')}" alt="${_('Git repository')}" src="${h.url("/images/icons/giticon.png")}"/>
%else:
%if repo['dbrepo']['private']:
<img class="icon" alt="${_('private')}" src="${h.url("/images/icons/lock.png")}"/>
<img class="icon" alt="${_('public')}" src="${h.url("/images/icons/lock_open.png")}"/>
${h.link_to(repo['repo'].name, h.url('summary_home',repo_name=repo['repo'].name),class_="repo_name")}
${h.link_to(repo['name'], h.url('summary_home',repo_name=repo['name']),class_="repo_name")}
%if repo['dbrepo_fork']:
<a href="${h.url('summary_home',repo_name=repo['dbrepo_fork']['repo_name'])}">
<img class="icon" alt="${_('public')}"
title="${_('Fork of')} ${repo['dbrepo_fork']['repo_name']}"
src="${h.url("/images/icons/arrow_divide.png")}"/></a>
</td>
<td><span class="tooltip" title="${repo['repo'].last_change}">${("r%s:%s") % (h.get_changeset_safe(repo['repo'],'tip').revision,h.short_id(h.get_changeset_safe(repo['repo'],'tip').raw_id))}</span></td>
<td><a href="${h.url('repo_settings_home',repo_name=repo['repo'].name)}" title="${_('edit')}"><img class="icon" alt="${_('private')}" src="${h.url("/images/icons/application_form_edit.png")}"/></a></td>
<td><a href="${h.url('repo_settings_home',repo_name=repo['name'])}" title="${_('edit')}"><img class="icon" alt="${_('private')}" src="${h.url("/images/icons/application_form_edit.png")}"/></a></td>
${h.form(url('repo_settings_delete', repo_name=repo['repo'].name),method='delete')}
${h.submit('remove_%s' % repo['repo'].name,'',class_="delete_icon action_button",onclick="return confirm('Confirm to delete this repository');")}
${h.form(url('repo_settings_delete', repo_name=repo['name']),method='delete')}
${h.submit('remove_%s' % repo['name'],'',class_="delete_icon action_button",onclick="return confirm('Confirm to delete this repository');")}
</tr>
%endfor
${_('No repositories yet')}
${h.link_to(_('create one now'),h.url('admin_settings_create_repository'))}
</tbody>
</table>
<script type="text/javascript">
var D = YAHOO.util.Dom;
var E = YAHOO.util.Event;
var S = YAHOO.util.Selector;
var q_filter = D.get('q_filter');
var F = YAHOO.namespace('q_filter');
E.on(q_filter,'click',function(){
q_filter.value = '';
F.filterTimeout = null;
F.updateFilter = function() {
// Reset timeout
var obsolete = [];
var nodes = S.query('div.table tr td a.repo_name');
var req = D.get('q_filter').value;
for (n in nodes){
D.setStyle(nodes[n].parentNode.parentNode,'display','')
if (req){
if (nodes[n].innerHTML.toLowerCase().indexOf(req) == -1) {
obsolete.push(nodes[n]);
if(obsolete){
for (n in obsolete){
D.setStyle(obsolete[n].parentNode.parentNode,'display','none');
E.on(q_filter,'keyup',function(e){
clearTimeout(F.filterTimeout);
setTimeout(F.updateFilter,600);
</script>
\ No newline at end of file
${c.repo_name} ${_('File annotate')} - ${c.rhodecode_name}
${h.link_to(u'Home',h.url('/'))}
»
${h.link_to(c.repo_name,h.url('summary_home',repo_name=c.repo_name))}
${_('annotate')} @ R${c.cs.revision}:${h.short_id(c.cs.raw_id)}
${self.menu('files')}
<div class="box">
<span style="text-transform: uppercase;"><a href="#">${_('branch')}: ${c.cs.branch}</a></span>
<div id="files_data">
<h3 class="files_location">${_('Location')}: ${h.files_breadcrumbs(c.repo_name,c.cs.revision,c.file.path)}</h3>
<dl class="overview">
<dt>${_('Revision')}</dt>
<dd>${h.link_to("r%s:%s" % (c.file.last_changeset.revision,h.short_id(c.file.last_changeset.raw_id)),
h.url('changeset_home',repo_name=c.repo_name,revision=c.file.last_changeset.raw_id))} </dd>
<dt>${_('Size')}</dt>
<dd>${h.format_byte_size(c.file.size,binary=True)}</dd>
<dt>${_('Mimetype')}</dt>
<dd>${c.file.mimetype}</dd>
<dt>${_('Options')}</dt>
<dd>${h.link_to(_('show source'),
h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path))}
/ ${h.link_to(_('show as raw'),
h.url('files_raw_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path))}
/ ${h.link_to(_('download as raw'),
h.url('files_rawfile_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path))}
</dd>
<dt>${_('History')}</dt>
<dd>
${h.form(h.url('files_diff_home',repo_name=c.repo_name,f_path=c.f_path),method='get')}
${h.hidden('diff2',c.file.last_changeset.raw_id)}
${h.select('diff1',c.file.last_changeset.raw_id,c.file_history)}
${h.submit('diff','diff to revision',class_="ui-button")}
${h.submit('show_rev','show at revision',class_="ui-button")}
</dl>
<div id="body" class="codeblock">
<div class="code-header">
<div class="revision">${c.file.name}@r${c.file.last_changeset.revision}:${h.short_id(c.file.last_changeset.raw_id)}</div>
<div class="commit">"${c.file.message}"</div>
<div class="code-body">
%if c.file.is_binary:
${_('Binary file')}
% if c.file.size < c.cut_off_limit:
${h.pygmentize_annotation(c.file,linenos=True,anchorlinenos=True,lineanchors='S',cssclass="code-highlight")}
${h.pygmentize_annotation(c.repo_name,c.file,linenos=True,anchorlinenos=True,lineanchors='S',cssclass="code-highlight")}
${_('File is to big to display')} ${h.link_to(_('show as raw'),
h.url('files_raw_home',repo_name=c.repo_name,revision=c.cs.revision,f_path=c.f_path))}
YAHOO.util.Event.onDOMReady(function(){
YAHOO.util.Event.addListener('show_rev','click',function(e){
YAHOO.util.Event.preventDefault(e);
var cs = YAHOO.util.Dom.get('diff1').value;
var url = "${h.url('files_annotate_home',repo_name=c.repo_name,revision='__CS__',f_path=c.f_path)}".replace('__CS__',cs);
window.location = url;
%for repo in c.repos_list:
<img src="${h.url("/images/icons/lock.png")}" alt="${_('Private repository')}" class="repo_switcher_type"/>
${h.link_to(repo['name'].name,h.url('summary_home',repo_name=repo['name']),class_="%s" % repo['dbrepo']['repo_type'])}
${h.link_to(repo['name'],h.url('summary_home',repo_name=repo['name']),class_="%s" % repo['dbrepo']['repo_type'])}
<img src="${h.url("/images/icons/lock_open.png")}" alt="${_('Public repository')}" class="repo_switcher_type" />
${c.repo_name} ${_('Summary')} - ${c.rhodecode_name}
${h.link_to(c.dbrepo.just_name,h.url('summary_home',repo_name=c.repo_name))}
${_('summary')}
${self.menu('summary')}
<label>${_('Name')}:</label>
<div class="input-short">
%if c.rhodecode_user.username != 'default':
%if c.following:
<span id="follow_toggle" class="following" title="${_('Stop following this repository')}"
onclick="javascript:toggleFollowingRepo(this,${c.dbrepo.repo_id},'${str(h.get_token())}')">
</span>
<span id="follow_toggle" class="follow" title="${_('Start following this repository')}"
%endif:
%if c.dbrepo.repo_type =='hg':
<img style="margin-bottom:2px" class="icon" title="${_('Mercurial repository')}" alt="${_('Mercurial repository')}" src="${h.url("/images/icons/hgicon.png")}"/>
%if c.dbrepo.repo_type =='git':
<img style="margin-bottom:2px" class="icon" title="${_('Git repository')}" alt="${_('Git repository')}" src="${h.url("/images/icons/giticon.png")}"/>
%if c.dbrepo.private:
<img style="margin-bottom:2px" class="icon" title="${_('private repository')}" alt="${_('private repository')}" src="${h.url("/images/icons/lock.png")}"/>
<img style="margin-bottom:2px" class="icon" title="${_('public repository')}" alt="${_('public repository')}" src="${h.url("/images/icons/lock_open.png")}"/>
<span style="font-size: 1.6em;font-weight: bold;vertical-align: baseline;">${c.repo.name}</span>
<br/>
<span style="font-size: 1.6em;font-weight: bold;vertical-align: baseline;">${h.repo_link(c.dbrepo.groups_and_repo)}</span>
%if c.dbrepo.fork:
<span style="margin-top:5px">
<a href="${h.url('summary_home',repo_name=c.dbrepo.fork.repo_name)}">
title="${_('Fork of')} ${c.dbrepo.fork.repo_name}"
src="${h.url("/images/icons/arrow_divide.png")}"/>
${_('Fork of')} ${c.dbrepo.fork.repo_name}
</a>
%if c.dbrepo.clone_uri:
<a href="${h.url(str(c.dbrepo.clone_uri))}">
<img class="icon" alt="${_('remote clone')}"
title="${_('Clone from')} ${c.dbrepo.clone_uri}"
src="${h.url("/images/icons/connect.png")}"/>
${_('Clone from')} ${c.dbrepo.clone_uri}
<label>${_('Description')}:</label>
${c.dbrepo.description}
<label>${_('Contact')}:</label>
<div class="gravatar">
<img alt="gravatar" src="${h.gravatar_url(c.dbrepo.user.email)}"/>
${_('Username')}: ${c.dbrepo.user.username}<br/>
${_('Name')}: ${c.dbrepo.user.name} ${c.dbrepo.user.lastname}<br/>
${_('Email')}: <a href="mailto:${c.dbrepo.user.email}">${c.dbrepo.user.email}</a>
<label>${_('Last change')}:</label>
${h.age(c.repo.last_change)} - ${c.repo.last_change}
${_('by')} ${h.get_changeset_safe(c.repo,'tip').author}
<b>${'r%s:%s' % (h.get_changeset_safe(c.rhodecode_repo,'tip').revision,
h.get_changeset_safe(c.rhodecode_repo,'tip').short_id)}</b> -
<span class="tooltip" title="${c.rhodecode_repo.last_change}">
${h.age(c.rhodecode_repo.last_change)}</span><br/>
${_('by')} ${h.get_changeset_safe(c.rhodecode_repo,'tip').author}
<label>${_('Clone url')}:</label>
<input type="text" id="clone_url" readonly="readonly" value="hg clone ${c.clone_repo_url}" size="70"/>
<label>${_('Trending source files')}:</label>
<div id="lang_stats"></div>
<label>${_('Download')}:</label>
%if len(c.repo.revisions) == 0:
%if len(c.rhodecode_repo.revisions) == 0:
${_('There are no downloads yet')}
%elif c.enable_downloads is False:
${_('Downloads are disabled for this repository')}
%if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
[${h.link_to(_('enable'),h.url('edit_repo',repo_name=c.repo_name))}]
${h.select('download_options',c.repo.get_changeset().raw_id,c.download_options)}
%for cnt,archive in enumerate(c.repo._get_archives()):
${h.select('download_options',c.rhodecode_repo.get_changeset().raw_id,c.download_options)}
%for cnt,archive in enumerate(c.rhodecode_repo._get_archives()):
%if cnt >=1:
|
<span class="tooltip" title="${_('Download %s as %s') %('tip',archive['type'])}"
id="${archive['type']+'_link'}">${h.link_to(archive['type'],
h.url('files_archive_home',repo_name=c.repo.name,
h.url('files_archive_home',repo_name=c.dbrepo.repo_name,
fname='tip'+archive['extension']),class_="archive_icon")}</span>
<label>${_('Feeds')}:</label>
${h.link_to(_('RSS'),h.url('rss_feed_home',repo_name=c.repo.name,api_key=c.rhodecode_user.api_key),class_='rss_icon')}
${h.link_to(_('Atom'),h.url('atom_feed_home',repo_name=c.repo.name,api_key=c.rhodecode_user.api_key),class_='atom_icon')}
${h.link_to(_('RSS'),h.url('rss_feed_home',repo_name=c.dbrepo.repo_name,api_key=c.rhodecode_user.api_key),class_='rss_icon')}
${h.link_to(_('Atom'),h.url('atom_feed_home',repo_name=c.dbrepo.repo_name,api_key=c.rhodecode_user.api_key),class_='atom_icon')}
${h.link_to(_('RSS'),h.url('rss_feed_home',repo_name=c.repo.name),class_='rss_icon')}
${h.link_to(_('Atom'),h.url('atom_feed_home',repo_name=c.repo.name),class_='atom_icon')}
${h.link_to(_('RSS'),h.url('rss_feed_home',repo_name=c.dbrepo.repo_name),class_='rss_icon')}
${h.link_to(_('Atom'),h.url('atom_feed_home',repo_name=c.dbrepo.repo_name),class_='atom_icon')}
YUE.onDOMReady(function(e){
id = 'clone_url';
YUE.on(id,'click',function(e){
YUD.get('clone_url').select();
})
var data = ${c.trending_languages|n};
var total = 0;
var no_data = true;
for (k in data){
total += data[k];
no_data = false;
var tbl = document.createElement('table');
tbl.setAttribute('class','trending_language_tbl');
var cnt =0;
cnt+=1;
var hide = cnt>2;
var tr = document.createElement('tr');
if (hide){
tr.setAttribute('style','display:none');
tr.setAttribute('class','stats_hidden');
var percentage = Math.round((data[k]/total*100),2);
var value = data[k];
var td1 = document.createElement('td');
td1.width=150;
var trending_language_label = document.createElement('div');
trending_language_label.innerHTML = k;
td1.appendChild(trending_language_label);
var td2 = document.createElement('td');
td2.setAttribute('style','padding-right:14px !important');
var trending_language = document.createElement('div');
var nr_files = value+" ${_('files')}";
trending_language.title = k+" "+nr_files;
if (percentage>20){
trending_language.innerHTML = "<b style='font-size:0.8em'>"+percentage+"% "+nr_files+ "</b>";
else{
trending_language.innerHTML = "<b style='font-size:0.8em'>"+percentage+"%</b>";
trending_language.setAttribute("class", 'trending_language top-right-rounded-corner bottom-right-rounded-corner');
trending_language.style.width=percentage+"%";
td2.appendChild(trending_language);
tr.appendChild(td1);
tr.appendChild(td2);
tbl.appendChild(tr);
if(cnt == 2){
var show_more = document.createElement('tr');
var td=document.createElement('td');
lnk = document.createElement('a');
lnk.href='#';
lnk.innerHTML = "${_("show more")}";
lnk.id='code_stats_show_more';
td.appendChild(lnk);
show_more.appendChild(td);
show_more.appendChild(document.createElement('td'));
tbl.appendChild(show_more);
if(no_data){
td1.innerHTML = "${c.no_data_msg}";
YUD.get('lang_stats').appendChild(tbl);
YUE.on('code_stats_show_more','click',function(){
l = YUD.getElementsByClassName('stats_hidden')
for (e in l){
YUD.setStyle(l[e],'display','');
YUD.setStyle(YUD.get('code_stats_show_more'),
'display','none');
YUE.on('download_options','change',function(e){
var new_cs = e.target.options[e.target.selectedIndex];
var tmpl_links = {}
tmpl_links['${archive['type']}'] = '${h.link_to(archive['type'],
fname='__CS__'+archive['extension']),class_="archive_icon")}';
for(k in tmpl_links){
var s = YUD.get(k+'_link')
title_tmpl = "${_('Download %s as %s') % ('__CS_NAME__',archive['type'])}";
s.title = title_tmpl.replace('__CS_NAME__',new_cs.text)
s.innerHTML = tmpl_links[k].replace('__CS__',new_cs.value);
<div class="box box-right" style="min-height:455px">
<h5>${_('Commit activity by day / author')}</h5>
%if c.no_data:
<div style="padding:0 10px 10px 15px;font-size: 1.2em;">${c.no_data_msg}
<div id="commit_history" style="width:460px;height:300px;float:left"></div>
<div style="clear: both;height: 10px"></div>
<div id="overview" style="width:460px;height:100px;float:left"></div>
<div id="legend_data" style="clear:both;margin-top:10px;">
<div id="legend_container"></div>
<div id="legend_choices">
<table id="legend_choices_tables" style="font-size:smaller;color:#545454"></table>
/**
* Plots summary graph
*
* @class SummaryPlot
* @param {from} initial from for detailed graph
* @param {to} initial to for detailed graph
* @param {dataset}
* @param {overview_dataset}
*/
function SummaryPlot(from,to,dataset,overview_dataset) {
var initial_ranges = {
"xaxis":{
"from":from,
"to":to,
},
var dataset = dataset;
var overview_dataset = [overview_dataset];
var choiceContainer = YUD.get("legend_choices");
var choiceContainerTable = YUD.get("legend_choices_tables");
var plotContainer = YUD.get('commit_history');
var overviewContainer = YUD.get('overview');
var plot_options = {
bars: {show:true,align:'center',lineWidth:4},
legend: {show:true, container:"legend_container"},
points: {show:true,radius:0,fill:false},
yaxis: {tickDecimals:0,},
xaxis: {
mode: "time",
timeformat: "%d/%m",
min:from,
max:to,
grid: {
hoverable: true,
clickable: true,
autoHighlight:true,
color: "#999"
//selection: {mode: "x"}
var overview_options = {
legend:{show:false},
bars: {show:true,barWidth: 2,},
shadowSize: 0,
xaxis: {mode: "time", timeformat: "%d/%m/%y",},
yaxis: {ticks: 3, min: 0,tickDecimals:0,},
grid: {color: "#999",},
selection: {mode: "x"}
*get dummy data needed in few places
function getDummyData(label){
return {"label":label,
"data":[{"time":0,
"commits":0,
"added":0,
"changed":0,
"removed":0,
}],
"schema":["commits"],
"color":'#ffffff',
* generate checkboxes accordindly to data
* @param keys
* @returns
function generateCheckboxes(data) {
//append checkboxes
var i = 0;
choiceContainerTable.innerHTML = '';
for(var pos in data) {
data[pos].color = i;
i++;
if(data[pos].label != ''){
choiceContainerTable.innerHTML += '<tr><td>'+
'<input type="checkbox" name="' + data[pos].label +'" checked="checked" />'
+data[pos].label+
'</td></tr>';
* ToolTip show
function showTooltip(x, y, contents) {
var div=document.getElementById('tooltip');
if(!div) {
div = document.createElement('div');
div.id="tooltip";
div.style.position="absolute";
div.style.border='1px solid #fdd';
div.style.padding='2px';
div.style.backgroundColor='#fee';
document.body.appendChild(div);
YUD.setStyle(div, 'opacity', 0);
div.innerHTML = contents;
div.style.top=(y + 5) + "px";
div.style.left=(x + 5) + "px";
var anim = new YAHOO.util.Anim(div, {opacity: {to: 0.8}}, 0.2);
anim.animate();
* This function will detect if selected period has some changesets
for this user if it does this data is then pushed for displaying
Additionally it will only display users that are selected by the checkbox
function getDataAccordingToRanges(ranges) {
var data = [];
var keys = [];
for(var key in dataset){
var push = false;
//method1 slow !!
//*
for(var ds in dataset[key].data){
commit_data = dataset[key].data[ds];
if (commit_data.time >= ranges.xaxis.from && commit_data.time <= ranges.xaxis.to){
push = true;
//*/
/*//method2 sorted commit data !!!
var first_commit = dataset[key].data[0].time;
var last_commit = dataset[key].data[dataset[key].data.length-1].time;
if (first_commit >= ranges.xaxis.from && last_commit <= ranges.xaxis.to){
if(push){
data.push(dataset[key]);
if(data.length >= 1){
from rhodecode.tests import *
class TestReposGroupsController(TestController):
def test_index(self):
response = self.app.get(url('repos_groups'))
# Test response...
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):
response = self.app.get(url('new_repos_group'))
def test_new_as_xml(self):
response = self.app.get(url('formatted_new_repos_group', format='xml'))
def test_update(self):
response = self.app.put(url('repos_group', id=1))
def test_update_browser_fakeout(self):
response = self.app.post(url('repos_group', id=1), params=dict(_method='put'))
def test_delete(self):
response = self.app.delete(url('repos_group', id=1))
def test_delete_browser_fakeout(self):
response = self.app.post(url('repos_group', id=1), params=dict(_method='delete'))
def test_show(self):
response = self.app.get(url('repos_group', id=1))
def test_show_as_xml(self):
response = self.app.get(url('formatted_repos_group', id=1, format='xml'))
def test_edit(self):
response = self.app.get(url('edit_repos_group', id=1))
def test_edit_as_xml(self):
response = self.app.get(url('formatted_edit_repos_group', id=1, format='xml'))
Status change: