Changeset - 7b67b0dcad6d
[Not reviewed]
beta
0 6 1
Marcin Kuzminski - 14 years ago 2011-09-22 03:33:29
marcin@python-works.com
Added initial support for creating new nodes in repos
7 files changed with 208 insertions and 16 deletions:
0 comments (0 inline, 0 general)
rhodecode/config/routing.py
Show inline comments
 
@@ -369,24 +369,29 @@ def make_map(config):
 
                 conditions=dict(function=check_repo))
 

	
 
    rmap.connect('files_annotate_home',
 
                 '/{repo_name:.*}/annotate/{revision}/{f_path:.*}',
 
                 controller='files', action='annotate', revision='tip',
 
                 f_path='', conditions=dict(function=check_repo))
 

	
 
    rmap.connect('files_edit_home',
 
                 '/{repo_name:.*}/edit/{revision}/{f_path:.*}',
 
                 controller='files', action='edit', revision='tip',
 
                 f_path='', conditions=dict(function=check_repo))
 

	
 
    rmap.connect('files_add_home',
 
                 '/{repo_name:.*}/add/{revision}/{f_path:.*}',
 
                 controller='files', action='add', revision='tip',
 
                 f_path='', conditions=dict(function=check_repo))
 

	
 
    rmap.connect('files_archive_home', '/{repo_name:.*}/archive/{fname}',
 
                controller='files', action='archivefile',
 
                conditions=dict(function=check_repo))
 

	
 
    rmap.connect('files_nodelist_home',
 
                 '/{repo_name:.*}/nodelist/{revision}/{f_path:.*}',
 
                controller='files', action='nodelist',
 
                conditions=dict(function=check_repo))
 

	
 
    rmap.connect('repo_settings_delete', '/{repo_name:.*}/settings',
 
                controller='settings', action="delete",
 
                conditions=dict(method=["DELETE"], function=check_repo))
rhodecode/controllers/files.py
Show inline comments
 
@@ -48,37 +48,44 @@ import rhodecode.lib.helpers as h
 
from rhodecode.model.repo import RepoModel
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class FilesController(BaseRepoController):
 

	
 
    @LoginRequired()
 
    def __before__(self):
 
        super(FilesController, self).__before__()
 
        c.cut_off_limit = self.cut_off_limit
 

	
 
    def __get_cs_or_redirect(self, rev, repo_name):
 
    def __get_cs_or_redirect(self, rev, repo_name, redirect_after=True):
 
        """
 
        Safe way to get changeset if error occur it redirects to tip with
 
        proper message
 

	
 
        :param rev: revision to fetch
 
        :param repo_name: repo name to redirect after
 
        """
 

	
 
        try:
 
            return c.rhodecode_repo.get_changeset(rev)
 
        except EmptyRepositoryError, e:
 
            h.flash(_('There are no files yet'), category='warning')
 
            if not redirect_after:
 
                return None
 
            url_ = url('files_add_home',
 
                       repo_name=c.repo_name,
 
                       revision=0,f_path='')
 
            add_new = '<a href="%s">[%s]</a>' % (url_,_('add new'))
 
            h.flash(h.literal(_('There are no files yet %s' % add_new)), 
 
                    category='warning')
 
            redirect(h.url('summary_home', repo_name=repo_name))
 

	
 
        except RepositoryError, e:
 
            h.flash(str(e), category='warning')
 
            redirect(h.url('files_home', repo_name=repo_name, revision='tip'))
 

	
 
    def __get_filenode_or_redirect(self, repo_name, cs, path):
 
        """
 
        Returns file_node, if error occurs or given path is directory,
 
        it'll redirect to top level path
 

	
 
        :param repo_name: repo_name
 
@@ -238,25 +245,24 @@ class FilesController(BaseRepoController
 

	
 
    @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
 
    def edit(self, repo_name, revision, f_path):
 
        r_post = request.POST
 

	
 
        c.cs = self.__get_cs_or_redirect(revision, repo_name)
 
        c.file = self.__get_filenode_or_redirect(repo_name, c.cs, f_path)
 

	
 
        if c.file.is_binary:
 
            return redirect(url('files_home', repo_name=c.repo_name,
 
                         revision=c.cs.raw_id, f_path=f_path))
 

	
 
        c.file_history = self._get_node_history(c.cs, f_path)
 
        c.f_path = f_path
 

	
 
        if r_post:
 

	
 
            old_content = c.file.content
 
            sl = old_content.splitlines(1)
 
            first_line = sl[0] if sl else ''
 
            # modes:  0 - Unix, 1 - Mac, 2 - DOS
 
            mode = detect_mode(first_line, 0)
 
            content = convert_line_endings(r_post.get('content'), mode)
 

	
 
            message = r_post.get('message') or (_('Edited %s via RhodeCode')
 
@@ -277,24 +283,67 @@ class FilesController(BaseRepoController
 
                                             content=content, f_path=f_path)
 
                h.flash(_('Successfully committed to %s' % f_path),
 
                        category='success')
 

	
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during commit'), category='error')
 
            return redirect(url('changeset_home',
 
                                repo_name=c.repo_name, revision='tip'))
 

	
 
        return render('files/files_edit.html')
 

	
 
    @HasRepoPermissionAnyDecorator('repository.write', 'repository.admin')
 
    def add(self, repo_name, revision, f_path):
 
        r_post = request.POST
 
        c.cs = self.__get_cs_or_redirect(revision, repo_name, 
 
                                         redirect_after=False)
 
        if c.cs is None:
 
            c.cs = EmptyChangeset(alias=c.rhodecode_repo.alias)
 

	
 
        c.f_path = f_path
 

	
 
        if r_post:
 
            unix_mode = 0
 
            content = convert_line_endings(r_post.get('content'), unix_mode)
 

	
 
            message = r_post.get('message') or (_('Added %s via RhodeCode')
 
                                                % (f_path))
 
            location = r_post.get('location')
 
            filename = r_post.get('filename')
 
            node_path = os.path.join(location, filename)
 
            author = self.rhodecode_user.full_contact
 

	
 
            if not content:
 
                h.flash(_('No content'), category='warning')
 
                return redirect(url('changeset_home', repo_name=c.repo_name,
 
                                    revision='tip'))
 

	
 
            try:
 
                self.scm_model.create_node(repo=c.rhodecode_repo,
 
                                             repo_name=repo_name, cs=c.cs,
 
                                             user=self.rhodecode_user,
 
                                             author=author, message=message,
 
                                             content=content, f_path=node_path)
 
                h.flash(_('Successfully committed to %s' % node_path),
 
                        category='success')
 

	
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during commit'), category='error')
 
            return redirect(url('changeset_home',
 
                                repo_name=c.repo_name, revision='tip'))
 

	
 
        return render('files/files_add.html')
 

	
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def archivefile(self, repo_name, fname):
 

	
 
        fileformat = None
 
        revision = None
 
        ext = None
 
        subrepos = request.GET.get('subrepos') == 'true'
 

	
 
        for a_type, ext_data in settings.ARCHIVE_SPECS.items():
 
            archive_spec = fname.split(ext_data[1])
 
            if len(archive_spec) == 2 and archive_spec[1] == '':
rhodecode/lib/utils.py
Show inline comments
 
@@ -33,24 +33,25 @@ from os.path import dirname as dn, join 
 

	
 
from paste.script.command import Command, BadCommand
 

	
 
from UserDict import DictMixin
 

	
 
from mercurial import ui, config, hg
 
from mercurial.error import RepoError
 

	
 
from webhelpers.text import collapse, remove_formatting, strip_tags
 

	
 
from vcs.backends.base import BaseChangeset
 
from vcs.utils.lazy import LazyProperty
 
from vcs import get_backend
 

	
 
from rhodecode.model import meta
 
from rhodecode.model.caching_query import FromCache
 
from rhodecode.model.db import Repository, User, RhodeCodeUi, UserLog, Group, \
 
    RhodeCodeSettings
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.user import UserModel
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def recursive_replace(str, replace=' '):
 
@@ -304,42 +305,47 @@ def invalidate_cache(cache_key, *args):
 

	
 
    if cache_key.startswith('get_repo_cached_'):
 
        name = cache_key.split('get_repo_cached_')[-1]
 
        ScmModel().mark_for_invalidation(name)
 

	
 

	
 
class EmptyChangeset(BaseChangeset):
 
    """
 
    An dummy empty changeset. It's possible to pass hash when creating
 
    an EmptyChangeset
 
    """
 

	
 
    def __init__(self, cs='0' * 40, repo=None,requested_revision=None):
 
    def __init__(self, cs='0' * 40, repo=None, requested_revision=None, alias=None):
 
        self._empty_cs = cs
 
        self.revision = -1
 
        self.message = ''
 
        self.author = ''
 
        self.date = ''
 
        self.repository = repo
 
        self.requested_revision = requested_revision
 
        
 
        self.alias = alias
 

	
 
    @LazyProperty
 
    def raw_id(self):
 
        """Returns raw string identifying this changeset, useful for web
 
        representation.
 
        """
 

	
 
        return self._empty_cs
 

	
 
    @LazyProperty
 
    def branch(self):
 
        return get_backend(self.alias).DEFAULT_BRANCH_NAME
 

	
 
    @LazyProperty
 
    def short_id(self):
 
        return self.raw_id[:12]
 

	
 
    def get_file_changeset(self, path):
 
        return self
 

	
 
    def get_file_content(self, path):
 
        return u''
 

	
 
    def get_file_size(self, path):
 
        return 0
 

	
 
@@ -593,12 +599,13 @@ class BasePasterCommand(Command):
 
        """
 
        raise NotImplementedError("Abstract Method.")
 

	
 
    def bootstrap_config(self, conf):
 
        """
 
        Loads the pylons configuration.
 
        """
 
        from pylons import config as pylonsconfig
 

	
 
        path_to_ini_file = os.path.realpath(conf)
 
        conf = paste.deploy.appconfig('config:' + path_to_ini_file)
 
        pylonsconfig.init_app(conf.global_conf, conf.local_conf)
 

	
rhodecode/model/scm.py
Show inline comments
 
@@ -30,25 +30,25 @@ import logging
 
from sqlalchemy.exc import DatabaseError
 

	
 
from vcs import get_backend
 
from vcs.exceptions import RepositoryError
 
from vcs.utils.lazy import LazyProperty
 
from vcs.nodes import FileNode
 

	
 
from rhodecode import BACKENDS
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib import safe_str
 
from rhodecode.lib.auth import HasRepoPermissionAny
 
from rhodecode.lib.utils import get_repos as get_filesystem_repos, make_ui, \
 
    action_logger
 
    action_logger, EmptyChangeset
 
from rhodecode.model import BaseModel
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.db import Repository, RhodeCodeUi, CacheInvalidation, \
 
    UserFollowing, UserLog
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UserTemp(object):
 
    def __init__(self, user_id):
 
        self.user_id = user_id
 

	
 
@@ -343,28 +343,60 @@ class ScmModel(BaseModel):
 
        m.change(FileNode(path, content))
 
        tip = m.commit(message=message,
 
                 author=author,
 
                 parents=[cs], branch=cs.branch)
 

	
 
        new_cs = tip.short_id
 
        action = 'push_local:%s' % new_cs
 

	
 
        action_logger(user, action, repo_name)
 

	
 
        self.mark_for_invalidation(repo_name)
 

	
 
    def create_node(self, repo, repo_name, cs, user, author, message, content,
 
                      f_path):
 
        if repo.alias == 'hg':
 
            from vcs.backends.hg import MercurialInMemoryChangeset as IMC
 
        elif repo.alias == 'git':
 
            from vcs.backends.git import GitInMemoryChangeset as IMC
 
        # decoding here will force that we have proper encoded values
 
        # in any other case this will throw exceptions and deny commit
 
        content = safe_str(content)
 
        message = safe_str(message)
 
        path = safe_str(f_path)
 
        author = safe_str(author)
 
        m = IMC(repo)
 

	
 
        if isinstance(cs, EmptyChangeset):
 
            # Emptychangeset means we we're editing empty repository
 
            parents = None
 
        else:
 
            parents = [cs]
 

	
 
        m.add(FileNode(path, content=content))
 
        tip = m.commit(message=message,
 
                 author=author,
 
                 parents=parents, branch=cs.branch)
 
        new_cs = tip.short_id
 
        action = 'push_local:%s' % new_cs
 

	
 
        action_logger(user, action, repo_name)
 

	
 
        self.mark_for_invalidation(repo_name)
 

	
 

	
 
    def get_unread_journal(self):
 
        return self.sa.query(UserLog).count()
 

	
 
    def _should_invalidate(self, repo_name):
 
        """Looks up database for invalidation signals for this repo_name
 

	
 
        :param repo_name:
 
        """
 

	
 
        ret = self.sa.query(CacheInvalidation)\
 
            .filter(CacheInvalidation.cache_key == repo_name)\
 
            .filter(CacheInvalidation.cache_active == False)\
 
            .scalar()
 

	
 
        return ret
 

	
rhodecode/public/css/style.css
Show inline comments
 
@@ -1858,40 +1858,52 @@ div.browserblock .browser-branch label {
 
color:#4A4A4A;
 
vertical-align:text-top;
 
}
 
 
div.browserblock .browser-header span {
 
margin-left:5px;
 
font-weight:700;
 
}
 
 
div.browserblock .browser-search{
 
	clear:both;
 
	padding:8px 8px 0px 5px;
 
}
 
 
div.browserblock .search_activate #filter_activate{
 
	height: 20px;
 
}
 
div.browserblock #node_filter_box {
 
}
 
 
div.browserblock .search_activate{
 
    float: left
 
}
 
 
div.browserblock .add_node{
 
    float: left;
 
    padding-left: 5px;
 
}
 
 
div.browserblock .search_activate #filter_activate,div.browserblock .add_node a{
 
	vertical-align: sub;
 
	border: 1px solid;
 
	padding:2px;
 
	-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;
 
	background: url("../images/button.png") repeat-x scroll 0 0 #E5E3E3;
 
	border-color: #DDDDDD #DDDDDD #C6C6C6 #C6C6C6;
 
	color: #515151;
 
}
 
 
div.browserblock .search_activate a:hover{
 
div.browserblock .search_activate a:hover,div.browserblock .add_node a:hover{
 
    text-decoration: none !important;    
 
}
 
 
div.browserblock .browser-body {
 
background:#EEE;
 
border-top:1px solid #CCC;
 
}
 
 
table.code-browser {
 
border-collapse:collapse;
 
width:100%;
 
}
rhodecode/templates/files/files_add.html
Show inline comments
 
new file 100644
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${c.repo_name} ${_('Edit file')} - ${c.rhodecode_name}
 
</%def>
 

	
 
<%def name="js_extra()">
 
<script type="text/javascript" src="${h.url('/js/codemirror.js')}"></script>
 
</%def>
 
<%def name="css_extra()">
 
<link rel="stylesheet" type="text/css" href="${h.url('/css/codemirror.css')}"/>
 
</%def>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(u'Home',h.url('/'))}
 
    &raquo;
 
    ${h.link_to(c.repo_name,h.url('summary_home',repo_name=c.repo_name))}
 
    &raquo;
 
    ${_('add file')} @ R${c.cs.revision}:${h.short_id(c.cs.raw_id)}
 
</%def>
 

	
 
<%def name="page_nav()">
 
		${self.menu('files')}     
 
</%def>
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
        <ul class="links">
 
            <li>
 
              <span style="text-transform: uppercase;">
 
              <a href="#">${_('branch')}: ${c.cs.branch}</a></span>
 
            </li>          
 
        </ul>          
 
    </div>
 
    <div class="table">
 
		<div id="files_data">
 
		  ${h.form(h.url.current(),method='post',id='eform')}
 
            <h3>${_('Add new file')}</h3>
 
            <div class="form">
 
                    <div class="fields">
 
                         <div class="field">
 
                            <div class="label">
 
                                <label for="location">${_('Location')}</label>
 
                            </div>
 
                            <div class="input">
 
                                <input type="text" value="${c.f_path}" size="30" name="location" id="location">
 
                            </div>
 
                         </div>
 
                                      
 
                        <div class="field">
 
                            <div class="label">
 
                                <label for="filename">${_('File Name')}:</label>
 
                            </div>
 
                            <div class="input">
 
                                <input type="text" value="" size="30" name="filename" id="filename">
 
                            </div>
 
                        </div>                                                    
 
                    </div>
 
            </div>            
 
			<div id="body" class="codeblock">
 
			    <pre id="editor_pre"></pre>
 
				<textarea id="editor" name="content" style="display:none"></textarea>
 
				<div style="padding-top: 10px;">${_('commit message')}</div>
 
				<textarea id="commit" name="message" style="height: 100px;width: 99%"></textarea>
 
			</div>
 
			<div style="text-align: right;padding-top: 5px">
 
			<input id="reset" type="button" value="${_('Reset')}" class="ui-button-small" />
 
			${h.submit('commit',_('Commit changes'),class_="ui-button-small-blue")}
 
			</div>
 
			${h.end_form()}
 
			<script type="text/javascript">
 
			 var myCodeMirror = CodeMirror.fromTextArea(YUD.get('editor'),{
 
	                mode:  "null",
 
	                lineNumbers:true
 
	              });
 
			 YUE.on('reset','click',function(){
 
				 window.location="${h.url('files_home',repo_name=c.repo_name,revision=c.cs.revision,f_path=c.f_path)}";
 
			 })
 
			</script>
 
		</div>    
 
    </div>
 
</div>    
 
</%def>   
 
\ No newline at end of file
rhodecode/templates/files/files_browser.html
Show inline comments
 
@@ -14,29 +14,30 @@
 
	          <a class="rev" href="${c.url_prev}" title="${_('previous revision')}">&laquo;</a>
 
	          ${h.text('at_rev',value=c.changeset.revision,size=5)}
 
	          <a class="rev" href="${c.url_next}" title="${_('next revision')}">&raquo;</a>
 
	          ## ${h.submit('view',_('view'),class_="ui-button-small")}
 
		    </div>           
 
			${h.end_form()}
 
		</div>
 
	    <div class="browser-branch">
 
	       ${h.checkbox('stay_at_branch',c.changeset.branch,c.changeset.branch==c.branch)}
 
	       <label>${_('follow current branch')}</label>
 
	    </div>
 
        <div class="browser-search">
 
            <div class="search_activate">
 
                <a id="filter_activate" href="#">${_('search file list')}</a>
 
            </div>
 
        
 
            
 
              <div id="search_activate_id" class="search_activate">
 
                  <a id="filter_activate" href="#">${_('search file list')}</a>
 
              </div>
 
              <div  id="add_node_id" class="add_node">
 
                  <a href="${h.url('files_add_home',repo_name=c.repo_name,revision=c.changeset.raw_id,f_path=c.f_path)}">${_('add new file')}</a>
 
              </div>        
 
        <div>
 
            <div id="node_filter_box_loading" style="display:none">${_('Loading file list...')}</div>
 
            <div id="node_filter_box" style="display:none">
 
            ${h.files_breadcrumbs(c.repo_name,c.changeset.raw_id,c.files_list.path)}/<input type="text" value="type to search..." name="filter" size="25" id="node_filter" autocomplete="off">
 
            
 
            <script type="text/javascript">
 
            
 
            YUE.on('stay_at_branch','click',function(e){
 
                if(e.target.checked){
 
                    var uri = "${h.url.current(branch='__BRANCH__')}"
 
                    uri = uri.replace('__BRANCH__',e.target.value);
 
                    window.location = uri;
 
@@ -58,25 +59,26 @@
 
            url  = url.replace('__FPATH__','${c.files_list.path}');
 

	
 
            node_url  = node_url.replace('__REPO__','${c.repo_name}');
 
            node_url  = node_url.replace('__REVISION__','${c.changeset.raw_id}');
 
            
 
            
 
            F.filterTimeout = null;
 
            var nodes = null;
 
            
 
            
 
            F.initFilter = function(){
 
              YUD.setStyle('node_filter_box_loading','display','');
 
              YUD.setStyle('filter_activate','display','none');
 
              YUD.setStyle('search_activate_id','display','none');
 
              YUD.setStyle('add_node_id','display','none');
 
              YUC.initHeader('X-PARTIAL-XHR',true);
 
              YUC.asyncRequest('GET',url,{
 
                  success:function(o){
 
                  	nodes = JSON.parse(o.responseText);
 
                  	YUD.setStyle('node_filter_box_loading','display','none');
 
                  	YUD.setStyle('node_filter_box','display','');
 
                  },
 
                  failure:function(o){
 
                      console.log('failed to load');
 
                  }
 
              },null);            
 
            }
0 comments (0 inline, 0 general)