##// END OF EJS Templates
scm: optimized get_nodes function....
marcink -
r3461:d0ff5601 default
parent child Browse files
Show More
@@ -1,914 +1,918 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Scm model for RhodeCode
22 Scm model for RhodeCode
23 """
23 """
24
24
25 import os.path
25 import os.path
26 import traceback
26 import traceback
27 import logging
27 import logging
28 import cStringIO
28 import cStringIO
29
29
30 from sqlalchemy import func
30 from sqlalchemy import func
31 from zope.cachedescriptors.property import Lazy as LazyProperty
31 from zope.cachedescriptors.property import Lazy as LazyProperty
32
32
33 import rhodecode
33 import rhodecode
34 from rhodecode.lib.vcs import get_backend
34 from rhodecode.lib.vcs import get_backend
35 from rhodecode.lib.vcs.exceptions import RepositoryError, NodeNotChangedError
35 from rhodecode.lib.vcs.exceptions import RepositoryError, NodeNotChangedError
36 from rhodecode.lib.vcs.nodes import FileNode
36 from rhodecode.lib.vcs.nodes import FileNode
37 from rhodecode.lib.vcs.backends.base import EmptyCommit
37 from rhodecode.lib.vcs.backends.base import EmptyCommit
38 from rhodecode.lib import helpers as h, rc_cache
38 from rhodecode.lib import helpers as h, rc_cache
39 from rhodecode.lib.auth import (
39 from rhodecode.lib.auth import (
40 HasRepoPermissionAny, HasRepoGroupPermissionAny,
40 HasRepoPermissionAny, HasRepoGroupPermissionAny,
41 HasUserGroupPermissionAny)
41 HasUserGroupPermissionAny)
42 from rhodecode.lib.exceptions import NonRelativePathError, IMCCommitError
42 from rhodecode.lib.exceptions import NonRelativePathError, IMCCommitError
43 from rhodecode.lib import hooks_utils
43 from rhodecode.lib import hooks_utils
44 from rhodecode.lib.utils import (
44 from rhodecode.lib.utils import (
45 get_filesystem_repos, make_db_config)
45 get_filesystem_repos, make_db_config)
46 from rhodecode.lib.utils2 import (safe_str, safe_unicode)
46 from rhodecode.lib.utils2 import (safe_str, safe_unicode)
47 from rhodecode.lib.system_info import get_system_info
47 from rhodecode.lib.system_info import get_system_info
48 from rhodecode.model import BaseModel
48 from rhodecode.model import BaseModel
49 from rhodecode.model.db import (
49 from rhodecode.model.db import (
50 Repository, CacheKey, UserFollowing, UserLog, User, RepoGroup,
50 Repository, CacheKey, UserFollowing, UserLog, User, RepoGroup,
51 PullRequest)
51 PullRequest)
52 from rhodecode.model.settings import VcsSettingsModel
52 from rhodecode.model.settings import VcsSettingsModel
53 from rhodecode.model.validation_schema.validators import url_validator, InvalidCloneUrl
53 from rhodecode.model.validation_schema.validators import url_validator, InvalidCloneUrl
54
54
55 log = logging.getLogger(__name__)
55 log = logging.getLogger(__name__)
56
56
57
57
58 class UserTemp(object):
58 class UserTemp(object):
59 def __init__(self, user_id):
59 def __init__(self, user_id):
60 self.user_id = user_id
60 self.user_id = user_id
61
61
62 def __repr__(self):
62 def __repr__(self):
63 return "<%s('id:%s')>" % (self.__class__.__name__, self.user_id)
63 return "<%s('id:%s')>" % (self.__class__.__name__, self.user_id)
64
64
65
65
66 class RepoTemp(object):
66 class RepoTemp(object):
67 def __init__(self, repo_id):
67 def __init__(self, repo_id):
68 self.repo_id = repo_id
68 self.repo_id = repo_id
69
69
70 def __repr__(self):
70 def __repr__(self):
71 return "<%s('id:%s')>" % (self.__class__.__name__, self.repo_id)
71 return "<%s('id:%s')>" % (self.__class__.__name__, self.repo_id)
72
72
73
73
74 class SimpleCachedRepoList(object):
74 class SimpleCachedRepoList(object):
75 """
75 """
76 Lighter version of of iteration of repos without the scm initialisation,
76 Lighter version of of iteration of repos without the scm initialisation,
77 and with cache usage
77 and with cache usage
78 """
78 """
79 def __init__(self, db_repo_list, repos_path, order_by=None, perm_set=None):
79 def __init__(self, db_repo_list, repos_path, order_by=None, perm_set=None):
80 self.db_repo_list = db_repo_list
80 self.db_repo_list = db_repo_list
81 self.repos_path = repos_path
81 self.repos_path = repos_path
82 self.order_by = order_by
82 self.order_by = order_by
83 self.reversed = (order_by or '').startswith('-')
83 self.reversed = (order_by or '').startswith('-')
84 if not perm_set:
84 if not perm_set:
85 perm_set = ['repository.read', 'repository.write',
85 perm_set = ['repository.read', 'repository.write',
86 'repository.admin']
86 'repository.admin']
87 self.perm_set = perm_set
87 self.perm_set = perm_set
88
88
89 def __len__(self):
89 def __len__(self):
90 return len(self.db_repo_list)
90 return len(self.db_repo_list)
91
91
92 def __repr__(self):
92 def __repr__(self):
93 return '<%s (%s)>' % (self.__class__.__name__, self.__len__())
93 return '<%s (%s)>' % (self.__class__.__name__, self.__len__())
94
94
95 def __iter__(self):
95 def __iter__(self):
96 for dbr in self.db_repo_list:
96 for dbr in self.db_repo_list:
97 # check permission at this level
97 # check permission at this level
98 has_perm = HasRepoPermissionAny(*self.perm_set)(
98 has_perm = HasRepoPermissionAny(*self.perm_set)(
99 dbr.repo_name, 'SimpleCachedRepoList check')
99 dbr.repo_name, 'SimpleCachedRepoList check')
100 if not has_perm:
100 if not has_perm:
101 continue
101 continue
102
102
103 tmp_d = {
103 tmp_d = {
104 'name': dbr.repo_name,
104 'name': dbr.repo_name,
105 'dbrepo': dbr.get_dict(),
105 'dbrepo': dbr.get_dict(),
106 'dbrepo_fork': dbr.fork.get_dict() if dbr.fork else {}
106 'dbrepo_fork': dbr.fork.get_dict() if dbr.fork else {}
107 }
107 }
108 yield tmp_d
108 yield tmp_d
109
109
110
110
111 class _PermCheckIterator(object):
111 class _PermCheckIterator(object):
112
112
113 def __init__(
113 def __init__(
114 self, obj_list, obj_attr, perm_set, perm_checker,
114 self, obj_list, obj_attr, perm_set, perm_checker,
115 extra_kwargs=None):
115 extra_kwargs=None):
116 """
116 """
117 Creates iterator from given list of objects, additionally
117 Creates iterator from given list of objects, additionally
118 checking permission for them from perm_set var
118 checking permission for them from perm_set var
119
119
120 :param obj_list: list of db objects
120 :param obj_list: list of db objects
121 :param obj_attr: attribute of object to pass into perm_checker
121 :param obj_attr: attribute of object to pass into perm_checker
122 :param perm_set: list of permissions to check
122 :param perm_set: list of permissions to check
123 :param perm_checker: callable to check permissions against
123 :param perm_checker: callable to check permissions against
124 """
124 """
125 self.obj_list = obj_list
125 self.obj_list = obj_list
126 self.obj_attr = obj_attr
126 self.obj_attr = obj_attr
127 self.perm_set = perm_set
127 self.perm_set = perm_set
128 self.perm_checker = perm_checker
128 self.perm_checker = perm_checker
129 self.extra_kwargs = extra_kwargs or {}
129 self.extra_kwargs = extra_kwargs or {}
130
130
131 def __len__(self):
131 def __len__(self):
132 return len(self.obj_list)
132 return len(self.obj_list)
133
133
134 def __repr__(self):
134 def __repr__(self):
135 return '<%s (%s)>' % (self.__class__.__name__, self.__len__())
135 return '<%s (%s)>' % (self.__class__.__name__, self.__len__())
136
136
137 def __iter__(self):
137 def __iter__(self):
138 checker = self.perm_checker(*self.perm_set)
138 checker = self.perm_checker(*self.perm_set)
139 for db_obj in self.obj_list:
139 for db_obj in self.obj_list:
140 # check permission at this level
140 # check permission at this level
141 name = getattr(db_obj, self.obj_attr, None)
141 name = getattr(db_obj, self.obj_attr, None)
142 if not checker(name, self.__class__.__name__, **self.extra_kwargs):
142 if not checker(name, self.__class__.__name__, **self.extra_kwargs):
143 continue
143 continue
144
144
145 yield db_obj
145 yield db_obj
146
146
147
147
148 class RepoList(_PermCheckIterator):
148 class RepoList(_PermCheckIterator):
149
149
150 def __init__(self, db_repo_list, perm_set=None, extra_kwargs=None):
150 def __init__(self, db_repo_list, perm_set=None, extra_kwargs=None):
151 if not perm_set:
151 if not perm_set:
152 perm_set = [
152 perm_set = [
153 'repository.read', 'repository.write', 'repository.admin']
153 'repository.read', 'repository.write', 'repository.admin']
154
154
155 super(RepoList, self).__init__(
155 super(RepoList, self).__init__(
156 obj_list=db_repo_list,
156 obj_list=db_repo_list,
157 obj_attr='repo_name', perm_set=perm_set,
157 obj_attr='repo_name', perm_set=perm_set,
158 perm_checker=HasRepoPermissionAny,
158 perm_checker=HasRepoPermissionAny,
159 extra_kwargs=extra_kwargs)
159 extra_kwargs=extra_kwargs)
160
160
161
161
162 class RepoGroupList(_PermCheckIterator):
162 class RepoGroupList(_PermCheckIterator):
163
163
164 def __init__(self, db_repo_group_list, perm_set=None, extra_kwargs=None):
164 def __init__(self, db_repo_group_list, perm_set=None, extra_kwargs=None):
165 if not perm_set:
165 if not perm_set:
166 perm_set = ['group.read', 'group.write', 'group.admin']
166 perm_set = ['group.read', 'group.write', 'group.admin']
167
167
168 super(RepoGroupList, self).__init__(
168 super(RepoGroupList, self).__init__(
169 obj_list=db_repo_group_list,
169 obj_list=db_repo_group_list,
170 obj_attr='group_name', perm_set=perm_set,
170 obj_attr='group_name', perm_set=perm_set,
171 perm_checker=HasRepoGroupPermissionAny,
171 perm_checker=HasRepoGroupPermissionAny,
172 extra_kwargs=extra_kwargs)
172 extra_kwargs=extra_kwargs)
173
173
174
174
175 class UserGroupList(_PermCheckIterator):
175 class UserGroupList(_PermCheckIterator):
176
176
177 def __init__(self, db_user_group_list, perm_set=None, extra_kwargs=None):
177 def __init__(self, db_user_group_list, perm_set=None, extra_kwargs=None):
178 if not perm_set:
178 if not perm_set:
179 perm_set = ['usergroup.read', 'usergroup.write', 'usergroup.admin']
179 perm_set = ['usergroup.read', 'usergroup.write', 'usergroup.admin']
180
180
181 super(UserGroupList, self).__init__(
181 super(UserGroupList, self).__init__(
182 obj_list=db_user_group_list,
182 obj_list=db_user_group_list,
183 obj_attr='users_group_name', perm_set=perm_set,
183 obj_attr='users_group_name', perm_set=perm_set,
184 perm_checker=HasUserGroupPermissionAny,
184 perm_checker=HasUserGroupPermissionAny,
185 extra_kwargs=extra_kwargs)
185 extra_kwargs=extra_kwargs)
186
186
187
187
188 class ScmModel(BaseModel):
188 class ScmModel(BaseModel):
189 """
189 """
190 Generic Scm Model
190 Generic Scm Model
191 """
191 """
192
192
193 @LazyProperty
193 @LazyProperty
194 def repos_path(self):
194 def repos_path(self):
195 """
195 """
196 Gets the repositories root path from database
196 Gets the repositories root path from database
197 """
197 """
198
198
199 settings_model = VcsSettingsModel(sa=self.sa)
199 settings_model = VcsSettingsModel(sa=self.sa)
200 return settings_model.get_repos_location()
200 return settings_model.get_repos_location()
201
201
202 def repo_scan(self, repos_path=None):
202 def repo_scan(self, repos_path=None):
203 """
203 """
204 Listing of repositories in given path. This path should not be a
204 Listing of repositories in given path. This path should not be a
205 repository itself. Return a dictionary of repository objects
205 repository itself. Return a dictionary of repository objects
206
206
207 :param repos_path: path to directory containing repositories
207 :param repos_path: path to directory containing repositories
208 """
208 """
209
209
210 if repos_path is None:
210 if repos_path is None:
211 repos_path = self.repos_path
211 repos_path = self.repos_path
212
212
213 log.info('scanning for repositories in %s', repos_path)
213 log.info('scanning for repositories in %s', repos_path)
214
214
215 config = make_db_config()
215 config = make_db_config()
216 config.set('extensions', 'largefiles', '')
216 config.set('extensions', 'largefiles', '')
217 repos = {}
217 repos = {}
218
218
219 for name, path in get_filesystem_repos(repos_path, recursive=True):
219 for name, path in get_filesystem_repos(repos_path, recursive=True):
220 # name need to be decomposed and put back together using the /
220 # name need to be decomposed and put back together using the /
221 # since this is internal storage separator for rhodecode
221 # since this is internal storage separator for rhodecode
222 name = Repository.normalize_repo_name(name)
222 name = Repository.normalize_repo_name(name)
223
223
224 try:
224 try:
225 if name in repos:
225 if name in repos:
226 raise RepositoryError('Duplicate repository name %s '
226 raise RepositoryError('Duplicate repository name %s '
227 'found in %s' % (name, path))
227 'found in %s' % (name, path))
228 elif path[0] in rhodecode.BACKENDS:
228 elif path[0] in rhodecode.BACKENDS:
229 klass = get_backend(path[0])
229 klass = get_backend(path[0])
230 repos[name] = klass(path[1], config=config)
230 repos[name] = klass(path[1], config=config)
231 except OSError:
231 except OSError:
232 continue
232 continue
233 log.debug('found %s paths with repositories', len(repos))
233 log.debug('found %s paths with repositories', len(repos))
234 return repos
234 return repos
235
235
236 def get_repos(self, all_repos=None, sort_key=None):
236 def get_repos(self, all_repos=None, sort_key=None):
237 """
237 """
238 Get all repositories from db and for each repo create it's
238 Get all repositories from db and for each repo create it's
239 backend instance and fill that backed with information from database
239 backend instance and fill that backed with information from database
240
240
241 :param all_repos: list of repository names as strings
241 :param all_repos: list of repository names as strings
242 give specific repositories list, good for filtering
242 give specific repositories list, good for filtering
243
243
244 :param sort_key: initial sorting of repositories
244 :param sort_key: initial sorting of repositories
245 """
245 """
246 if all_repos is None:
246 if all_repos is None:
247 all_repos = self.sa.query(Repository)\
247 all_repos = self.sa.query(Repository)\
248 .filter(Repository.group_id == None)\
248 .filter(Repository.group_id == None)\
249 .order_by(func.lower(Repository.repo_name)).all()
249 .order_by(func.lower(Repository.repo_name)).all()
250 repo_iter = SimpleCachedRepoList(
250 repo_iter = SimpleCachedRepoList(
251 all_repos, repos_path=self.repos_path, order_by=sort_key)
251 all_repos, repos_path=self.repos_path, order_by=sort_key)
252 return repo_iter
252 return repo_iter
253
253
254 def get_repo_groups(self, all_groups=None):
254 def get_repo_groups(self, all_groups=None):
255 if all_groups is None:
255 if all_groups is None:
256 all_groups = RepoGroup.query()\
256 all_groups = RepoGroup.query()\
257 .filter(RepoGroup.group_parent_id == None).all()
257 .filter(RepoGroup.group_parent_id == None).all()
258 return [x for x in RepoGroupList(all_groups)]
258 return [x for x in RepoGroupList(all_groups)]
259
259
260 def mark_for_invalidation(self, repo_name, delete=False):
260 def mark_for_invalidation(self, repo_name, delete=False):
261 """
261 """
262 Mark caches of this repo invalid in the database. `delete` flag
262 Mark caches of this repo invalid in the database. `delete` flag
263 removes the cache entries
263 removes the cache entries
264
264
265 :param repo_name: the repo_name for which caches should be marked
265 :param repo_name: the repo_name for which caches should be marked
266 invalid, or deleted
266 invalid, or deleted
267 :param delete: delete the entry keys instead of setting bool
267 :param delete: delete the entry keys instead of setting bool
268 flag on them, and also purge caches used by the dogpile
268 flag on them, and also purge caches used by the dogpile
269 """
269 """
270 repo = Repository.get_by_repo_name(repo_name)
270 repo = Repository.get_by_repo_name(repo_name)
271
271
272 if repo:
272 if repo:
273 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
273 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
274 repo_id=repo.repo_id)
274 repo_id=repo.repo_id)
275 CacheKey.set_invalidate(invalidation_namespace, delete=delete)
275 CacheKey.set_invalidate(invalidation_namespace, delete=delete)
276
276
277 repo_id = repo.repo_id
277 repo_id = repo.repo_id
278 config = repo._config
278 config = repo._config
279 config.set('extensions', 'largefiles', '')
279 config.set('extensions', 'largefiles', '')
280 repo.update_commit_cache(config=config, cs_cache=None)
280 repo.update_commit_cache(config=config, cs_cache=None)
281 if delete:
281 if delete:
282 cache_namespace_uid = 'cache_repo.{}'.format(repo_id)
282 cache_namespace_uid = 'cache_repo.{}'.format(repo_id)
283 rc_cache.clear_cache_namespace('cache_repo', cache_namespace_uid)
283 rc_cache.clear_cache_namespace('cache_repo', cache_namespace_uid)
284
284
285 def toggle_following_repo(self, follow_repo_id, user_id):
285 def toggle_following_repo(self, follow_repo_id, user_id):
286
286
287 f = self.sa.query(UserFollowing)\
287 f = self.sa.query(UserFollowing)\
288 .filter(UserFollowing.follows_repo_id == follow_repo_id)\
288 .filter(UserFollowing.follows_repo_id == follow_repo_id)\
289 .filter(UserFollowing.user_id == user_id).scalar()
289 .filter(UserFollowing.user_id == user_id).scalar()
290
290
291 if f is not None:
291 if f is not None:
292 try:
292 try:
293 self.sa.delete(f)
293 self.sa.delete(f)
294 return
294 return
295 except Exception:
295 except Exception:
296 log.error(traceback.format_exc())
296 log.error(traceback.format_exc())
297 raise
297 raise
298
298
299 try:
299 try:
300 f = UserFollowing()
300 f = UserFollowing()
301 f.user_id = user_id
301 f.user_id = user_id
302 f.follows_repo_id = follow_repo_id
302 f.follows_repo_id = follow_repo_id
303 self.sa.add(f)
303 self.sa.add(f)
304 except Exception:
304 except Exception:
305 log.error(traceback.format_exc())
305 log.error(traceback.format_exc())
306 raise
306 raise
307
307
308 def toggle_following_user(self, follow_user_id, user_id):
308 def toggle_following_user(self, follow_user_id, user_id):
309 f = self.sa.query(UserFollowing)\
309 f = self.sa.query(UserFollowing)\
310 .filter(UserFollowing.follows_user_id == follow_user_id)\
310 .filter(UserFollowing.follows_user_id == follow_user_id)\
311 .filter(UserFollowing.user_id == user_id).scalar()
311 .filter(UserFollowing.user_id == user_id).scalar()
312
312
313 if f is not None:
313 if f is not None:
314 try:
314 try:
315 self.sa.delete(f)
315 self.sa.delete(f)
316 return
316 return
317 except Exception:
317 except Exception:
318 log.error(traceback.format_exc())
318 log.error(traceback.format_exc())
319 raise
319 raise
320
320
321 try:
321 try:
322 f = UserFollowing()
322 f = UserFollowing()
323 f.user_id = user_id
323 f.user_id = user_id
324 f.follows_user_id = follow_user_id
324 f.follows_user_id = follow_user_id
325 self.sa.add(f)
325 self.sa.add(f)
326 except Exception:
326 except Exception:
327 log.error(traceback.format_exc())
327 log.error(traceback.format_exc())
328 raise
328 raise
329
329
330 def is_following_repo(self, repo_name, user_id, cache=False):
330 def is_following_repo(self, repo_name, user_id, cache=False):
331 r = self.sa.query(Repository)\
331 r = self.sa.query(Repository)\
332 .filter(Repository.repo_name == repo_name).scalar()
332 .filter(Repository.repo_name == repo_name).scalar()
333
333
334 f = self.sa.query(UserFollowing)\
334 f = self.sa.query(UserFollowing)\
335 .filter(UserFollowing.follows_repository == r)\
335 .filter(UserFollowing.follows_repository == r)\
336 .filter(UserFollowing.user_id == user_id).scalar()
336 .filter(UserFollowing.user_id == user_id).scalar()
337
337
338 return f is not None
338 return f is not None
339
339
340 def is_following_user(self, username, user_id, cache=False):
340 def is_following_user(self, username, user_id, cache=False):
341 u = User.get_by_username(username)
341 u = User.get_by_username(username)
342
342
343 f = self.sa.query(UserFollowing)\
343 f = self.sa.query(UserFollowing)\
344 .filter(UserFollowing.follows_user == u)\
344 .filter(UserFollowing.follows_user == u)\
345 .filter(UserFollowing.user_id == user_id).scalar()
345 .filter(UserFollowing.user_id == user_id).scalar()
346
346
347 return f is not None
347 return f is not None
348
348
349 def get_followers(self, repo):
349 def get_followers(self, repo):
350 repo = self._get_repo(repo)
350 repo = self._get_repo(repo)
351
351
352 return self.sa.query(UserFollowing)\
352 return self.sa.query(UserFollowing)\
353 .filter(UserFollowing.follows_repository == repo).count()
353 .filter(UserFollowing.follows_repository == repo).count()
354
354
355 def get_forks(self, repo):
355 def get_forks(self, repo):
356 repo = self._get_repo(repo)
356 repo = self._get_repo(repo)
357 return self.sa.query(Repository)\
357 return self.sa.query(Repository)\
358 .filter(Repository.fork == repo).count()
358 .filter(Repository.fork == repo).count()
359
359
360 def get_pull_requests(self, repo):
360 def get_pull_requests(self, repo):
361 repo = self._get_repo(repo)
361 repo = self._get_repo(repo)
362 return self.sa.query(PullRequest)\
362 return self.sa.query(PullRequest)\
363 .filter(PullRequest.target_repo == repo)\
363 .filter(PullRequest.target_repo == repo)\
364 .filter(PullRequest.status != PullRequest.STATUS_CLOSED).count()
364 .filter(PullRequest.status != PullRequest.STATUS_CLOSED).count()
365
365
366 def mark_as_fork(self, repo, fork, user):
366 def mark_as_fork(self, repo, fork, user):
367 repo = self._get_repo(repo)
367 repo = self._get_repo(repo)
368 fork = self._get_repo(fork)
368 fork = self._get_repo(fork)
369 if fork and repo.repo_id == fork.repo_id:
369 if fork and repo.repo_id == fork.repo_id:
370 raise Exception("Cannot set repository as fork of itself")
370 raise Exception("Cannot set repository as fork of itself")
371
371
372 if fork and repo.repo_type != fork.repo_type:
372 if fork and repo.repo_type != fork.repo_type:
373 raise RepositoryError(
373 raise RepositoryError(
374 "Cannot set repository as fork of repository with other type")
374 "Cannot set repository as fork of repository with other type")
375
375
376 repo.fork = fork
376 repo.fork = fork
377 self.sa.add(repo)
377 self.sa.add(repo)
378 return repo
378 return repo
379
379
380 def pull_changes(self, repo, username, remote_uri=None, validate_uri=True):
380 def pull_changes(self, repo, username, remote_uri=None, validate_uri=True):
381 dbrepo = self._get_repo(repo)
381 dbrepo = self._get_repo(repo)
382 remote_uri = remote_uri or dbrepo.clone_uri
382 remote_uri = remote_uri or dbrepo.clone_uri
383 if not remote_uri:
383 if not remote_uri:
384 raise Exception("This repository doesn't have a clone uri")
384 raise Exception("This repository doesn't have a clone uri")
385
385
386 repo = dbrepo.scm_instance(cache=False)
386 repo = dbrepo.scm_instance(cache=False)
387 repo.config.clear_section('hooks')
387 repo.config.clear_section('hooks')
388
388
389 try:
389 try:
390 # NOTE(marcink): add extra validation so we skip invalid urls
390 # NOTE(marcink): add extra validation so we skip invalid urls
391 # this is due this tasks can be executed via scheduler without
391 # this is due this tasks can be executed via scheduler without
392 # proper validation of remote_uri
392 # proper validation of remote_uri
393 if validate_uri:
393 if validate_uri:
394 config = make_db_config(clear_session=False)
394 config = make_db_config(clear_session=False)
395 url_validator(remote_uri, dbrepo.repo_type, config)
395 url_validator(remote_uri, dbrepo.repo_type, config)
396 except InvalidCloneUrl:
396 except InvalidCloneUrl:
397 raise
397 raise
398
398
399 repo_name = dbrepo.repo_name
399 repo_name = dbrepo.repo_name
400 try:
400 try:
401 # TODO: we need to make sure those operations call proper hooks !
401 # TODO: we need to make sure those operations call proper hooks !
402 repo.fetch(remote_uri)
402 repo.fetch(remote_uri)
403
403
404 self.mark_for_invalidation(repo_name)
404 self.mark_for_invalidation(repo_name)
405 except Exception:
405 except Exception:
406 log.error(traceback.format_exc())
406 log.error(traceback.format_exc())
407 raise
407 raise
408
408
409 def push_changes(self, repo, username, remote_uri=None, validate_uri=True):
409 def push_changes(self, repo, username, remote_uri=None, validate_uri=True):
410 dbrepo = self._get_repo(repo)
410 dbrepo = self._get_repo(repo)
411 remote_uri = remote_uri or dbrepo.push_uri
411 remote_uri = remote_uri or dbrepo.push_uri
412 if not remote_uri:
412 if not remote_uri:
413 raise Exception("This repository doesn't have a clone uri")
413 raise Exception("This repository doesn't have a clone uri")
414
414
415 repo = dbrepo.scm_instance(cache=False)
415 repo = dbrepo.scm_instance(cache=False)
416 repo.config.clear_section('hooks')
416 repo.config.clear_section('hooks')
417
417
418 try:
418 try:
419 # NOTE(marcink): add extra validation so we skip invalid urls
419 # NOTE(marcink): add extra validation so we skip invalid urls
420 # this is due this tasks can be executed via scheduler without
420 # this is due this tasks can be executed via scheduler without
421 # proper validation of remote_uri
421 # proper validation of remote_uri
422 if validate_uri:
422 if validate_uri:
423 config = make_db_config(clear_session=False)
423 config = make_db_config(clear_session=False)
424 url_validator(remote_uri, dbrepo.repo_type, config)
424 url_validator(remote_uri, dbrepo.repo_type, config)
425 except InvalidCloneUrl:
425 except InvalidCloneUrl:
426 raise
426 raise
427
427
428 try:
428 try:
429 repo.push(remote_uri)
429 repo.push(remote_uri)
430 except Exception:
430 except Exception:
431 log.error(traceback.format_exc())
431 log.error(traceback.format_exc())
432 raise
432 raise
433
433
434 def commit_change(self, repo, repo_name, commit, user, author, message,
434 def commit_change(self, repo, repo_name, commit, user, author, message,
435 content, f_path):
435 content, f_path):
436 """
436 """
437 Commits changes
437 Commits changes
438
438
439 :param repo: SCM instance
439 :param repo: SCM instance
440
440
441 """
441 """
442 user = self._get_user(user)
442 user = self._get_user(user)
443
443
444 # decoding here will force that we have proper encoded values
444 # decoding here will force that we have proper encoded values
445 # in any other case this will throw exceptions and deny commit
445 # in any other case this will throw exceptions and deny commit
446 content = safe_str(content)
446 content = safe_str(content)
447 path = safe_str(f_path)
447 path = safe_str(f_path)
448 # message and author needs to be unicode
448 # message and author needs to be unicode
449 # proper backend should then translate that into required type
449 # proper backend should then translate that into required type
450 message = safe_unicode(message)
450 message = safe_unicode(message)
451 author = safe_unicode(author)
451 author = safe_unicode(author)
452 imc = repo.in_memory_commit
452 imc = repo.in_memory_commit
453 imc.change(FileNode(path, content, mode=commit.get_file_mode(f_path)))
453 imc.change(FileNode(path, content, mode=commit.get_file_mode(f_path)))
454 try:
454 try:
455 # TODO: handle pre-push action !
455 # TODO: handle pre-push action !
456 tip = imc.commit(
456 tip = imc.commit(
457 message=message, author=author, parents=[commit],
457 message=message, author=author, parents=[commit],
458 branch=commit.branch)
458 branch=commit.branch)
459 except Exception as e:
459 except Exception as e:
460 log.error(traceback.format_exc())
460 log.error(traceback.format_exc())
461 raise IMCCommitError(str(e))
461 raise IMCCommitError(str(e))
462 finally:
462 finally:
463 # always clear caches, if commit fails we want fresh object also
463 # always clear caches, if commit fails we want fresh object also
464 self.mark_for_invalidation(repo_name)
464 self.mark_for_invalidation(repo_name)
465
465
466 # We trigger the post-push action
466 # We trigger the post-push action
467 hooks_utils.trigger_post_push_hook(
467 hooks_utils.trigger_post_push_hook(
468 username=user.username, action='push_local', hook_type='post_push',
468 username=user.username, action='push_local', hook_type='post_push',
469 repo_name=repo_name, repo_alias=repo.alias, commit_ids=[tip.raw_id])
469 repo_name=repo_name, repo_alias=repo.alias, commit_ids=[tip.raw_id])
470 return tip
470 return tip
471
471
472 def _sanitize_path(self, f_path):
472 def _sanitize_path(self, f_path):
473 if f_path.startswith('/') or f_path.startswith('./') or '../' in f_path:
473 if f_path.startswith('/') or f_path.startswith('./') or '../' in f_path:
474 raise NonRelativePathError('%s is not an relative path' % f_path)
474 raise NonRelativePathError('%s is not an relative path' % f_path)
475 if f_path:
475 if f_path:
476 f_path = os.path.normpath(f_path)
476 f_path = os.path.normpath(f_path)
477 return f_path
477 return f_path
478
478
479 def get_dirnode_metadata(self, request, commit, dir_node):
479 def get_dirnode_metadata(self, request, commit, dir_node):
480 if not dir_node.is_dir():
480 if not dir_node.is_dir():
481 return []
481 return []
482
482
483 data = []
483 data = []
484 for node in dir_node:
484 for node in dir_node:
485 if not node.is_file():
485 if not node.is_file():
486 # we skip file-nodes
486 # we skip file-nodes
487 continue
487 continue
488
488
489 last_commit = node.last_commit
489 last_commit = node.last_commit
490 last_commit_date = last_commit.date
490 last_commit_date = last_commit.date
491 data.append({
491 data.append({
492 'name': node.name,
492 'name': node.name,
493 'size': h.format_byte_size_binary(node.size),
493 'size': h.format_byte_size_binary(node.size),
494 'modified_at': h.format_date(last_commit_date),
494 'modified_at': h.format_date(last_commit_date),
495 'modified_ts': last_commit_date.isoformat(),
495 'modified_ts': last_commit_date.isoformat(),
496 'revision': last_commit.revision,
496 'revision': last_commit.revision,
497 'short_id': last_commit.short_id,
497 'short_id': last_commit.short_id,
498 'message': h.escape(last_commit.message),
498 'message': h.escape(last_commit.message),
499 'author': h.escape(last_commit.author),
499 'author': h.escape(last_commit.author),
500 'user_profile': h.gravatar_with_user(
500 'user_profile': h.gravatar_with_user(
501 request, last_commit.author),
501 request, last_commit.author),
502 })
502 })
503
503
504 return data
504 return data
505
505
506 def get_nodes(self, repo_name, commit_id, root_path='/', flat=True,
506 def get_nodes(self, repo_name, commit_id, root_path='/', flat=True,
507 extended_info=False, content=False, max_file_bytes=None):
507 extended_info=False, content=False, max_file_bytes=None):
508 """
508 """
509 recursive walk in root dir and return a set of all path in that dir
509 recursive walk in root dir and return a set of all path in that dir
510 based on repository walk function
510 based on repository walk function
511
511
512 :param repo_name: name of repository
512 :param repo_name: name of repository
513 :param commit_id: commit id for which to list nodes
513 :param commit_id: commit id for which to list nodes
514 :param root_path: root path to list
514 :param root_path: root path to list
515 :param flat: return as a list, if False returns a dict with description
515 :param flat: return as a list, if False returns a dict with description
516 :param extended_info: show additional info such as md5, binary, size etc
517 :param content: add nodes content to the return data
516 :param max_file_bytes: will not return file contents over this limit
518 :param max_file_bytes: will not return file contents over this limit
517
519
518 """
520 """
519 _files = list()
521 _files = list()
520 _dirs = list()
522 _dirs = list()
521 try:
523 try:
522 _repo = self._get_repo(repo_name)
524 _repo = self._get_repo(repo_name)
523 commit = _repo.scm_instance().get_commit(commit_id=commit_id)
525 commit = _repo.scm_instance().get_commit(commit_id=commit_id)
524 root_path = root_path.lstrip('/')
526 root_path = root_path.lstrip('/')
525 for __, dirs, files in commit.walk(root_path):
527 for __, dirs, files in commit.walk(root_path):
528
526 for f in files:
529 for f in files:
527 _content = None
530 _content = None
528 _data = f.unicode_path
531 _data = f_name = f.unicode_path
529 over_size_limit = (max_file_bytes is not None
530 and f.size > max_file_bytes)
531
532
532 if not flat:
533 if not flat:
533 _data = {
534 _data = {
534 "name": h.escape(f.unicode_path),
535 "name": h.escape(f_name),
535 "type": "file",
536 "type": "file",
536 }
537 }
537 if extended_info:
538 if extended_info:
538 _data.update({
539 _data.update({
539 "md5": f.md5,
540 "md5": f.md5,
540 "binary": f.is_binary,
541 "binary": f.is_binary,
541 "size": f.size,
542 "size": f.size,
542 "extension": f.extension,
543 "extension": f.extension,
543 "mimetype": f.mimetype,
544 "mimetype": f.mimetype,
544 "lines": f.lines()[0]
545 "lines": f.lines()[0]
545 })
546 })
546
547
547 if content:
548 if content:
549 over_size_limit = (max_file_bytes is not None
550 and f.size > max_file_bytes)
548 full_content = None
551 full_content = None
549 if not f.is_binary and not over_size_limit:
552 if not f.is_binary and not over_size_limit:
550 full_content = safe_str(f.content)
553 full_content = safe_str(f.content)
551
554
552 _data.update({
555 _data.update({
553 "content": full_content,
556 "content": full_content,
554 })
557 })
555 _files.append(_data)
558 _files.append(_data)
559
556 for d in dirs:
560 for d in dirs:
557 _data = d.unicode_path
561 _data = d_name = d.unicode_path
558 if not flat:
562 if not flat:
559 _data = {
563 _data = {
560 "name": h.escape(d.unicode_path),
564 "name": h.escape(d_name),
561 "type": "dir",
565 "type": "dir",
562 }
566 }
563 if extended_info:
567 if extended_info:
564 _data.update({
568 _data.update({
565 "md5": None,
569 "md5": None,
566 "binary": None,
570 "binary": None,
567 "size": None,
571 "size": None,
568 "extension": None,
572 "extension": None,
569 })
573 })
570 if content:
574 if content:
571 _data.update({
575 _data.update({
572 "content": None
576 "content": None
573 })
577 })
574 _dirs.append(_data)
578 _dirs.append(_data)
575 except RepositoryError:
579 except RepositoryError:
576 log.exception("Exception in get_nodes")
580 log.exception("Exception in get_nodes")
577 raise
581 raise
578
582
579 return _dirs, _files
583 return _dirs, _files
580
584
581 def get_node(self, repo_name, commit_id, file_path,
585 def get_node(self, repo_name, commit_id, file_path,
582 extended_info=False, content=False, max_file_bytes=None):
586 extended_info=False, content=False, max_file_bytes=None):
583 """
587 """
584 retrieve single node from commit
588 retrieve single node from commit
585 """
589 """
586 try:
590 try:
587
591
588 _repo = self._get_repo(repo_name)
592 _repo = self._get_repo(repo_name)
589 commit = _repo.scm_instance().get_commit(commit_id=commit_id)
593 commit = _repo.scm_instance().get_commit(commit_id=commit_id)
590
594
591 file_node = commit.get_node(file_path)
595 file_node = commit.get_node(file_path)
592 if file_node.is_dir():
596 if file_node.is_dir():
593 raise RepositoryError('The given path is a directory')
597 raise RepositoryError('The given path is a directory')
594
598
595 _content = None
599 _content = None
596 f_name = file_node.unicode_path
600 f_name = file_node.unicode_path
597
601
598 file_data = {
602 file_data = {
599 "name": h.escape(f_name),
603 "name": h.escape(f_name),
600 "type": "file",
604 "type": "file",
601 }
605 }
602
606
603 if extended_info:
607 if extended_info:
604 file_data.update({
608 file_data.update({
605 "md5": file_node.md5,
609 "md5": file_node.md5,
606 "binary": file_node.is_binary,
610 "binary": file_node.is_binary,
607 "size": file_node.size,
611 "size": file_node.size,
608 "extension": file_node.extension,
612 "extension": file_node.extension,
609 "mimetype": file_node.mimetype,
613 "mimetype": file_node.mimetype,
610 "lines": file_node.lines()[0]
614 "lines": file_node.lines()[0]
611 })
615 })
612
616
613 if content:
617 if content:
614 over_size_limit = (max_file_bytes is not None
618 over_size_limit = (max_file_bytes is not None
615 and file_node.size > max_file_bytes)
619 and file_node.size > max_file_bytes)
616 full_content = None
620 full_content = None
617 if not file_node.is_binary and not over_size_limit:
621 if not file_node.is_binary and not over_size_limit:
618 full_content = safe_str(file_node.content)
622 full_content = safe_str(file_node.content)
619
623
620 file_data.update({
624 file_data.update({
621 "content": full_content,
625 "content": full_content,
622 })
626 })
623
627
624 except RepositoryError:
628 except RepositoryError:
625 log.exception("Exception in get_node")
629 log.exception("Exception in get_node")
626 raise
630 raise
627
631
628 return file_data
632 return file_data
629
633
630 def get_fts_data(self, repo_name, commit_id, root_path='/'):
634 def get_fts_data(self, repo_name, commit_id, root_path='/'):
631 """
635 """
632 Fetch node tree for usage in full text search
636 Fetch node tree for usage in full text search
633 """
637 """
634
638
635 tree_info = list()
639 tree_info = list()
636
640
637 try:
641 try:
638 _repo = self._get_repo(repo_name)
642 _repo = self._get_repo(repo_name)
639 commit = _repo.scm_instance().get_commit(commit_id=commit_id)
643 commit = _repo.scm_instance().get_commit(commit_id=commit_id)
640 root_path = root_path.lstrip('/')
644 root_path = root_path.lstrip('/')
641 for __, dirs, files in commit.walk(root_path):
645 for __, dirs, files in commit.walk(root_path):
642
646
643 for f in files:
647 for f in files:
644 _content = None
648 _content = None
645 _data = f_name = f.unicode_path
649 _data = f_name = f.unicode_path
646 is_binary, md5, size = f.metadata_uncached()
650 is_binary, md5, size = f.metadata_uncached()
647 _data = {
651 _data = {
648 "name": h.escape(f_name),
652 "name": h.escape(f_name),
649 "md5": md5,
653 "md5": md5,
650 "extension": f.extension,
654 "extension": f.extension,
651 "binary": is_binary,
655 "binary": is_binary,
652 "size": size
656 "size": size
653 }
657 }
654
658
655 tree_info.append(_data)
659 tree_info.append(_data)
656
660
657 except RepositoryError:
661 except RepositoryError:
658 log.exception("Exception in get_nodes")
662 log.exception("Exception in get_nodes")
659 raise
663 raise
660
664
661 return tree_info
665 return tree_info
662
666
663 def create_nodes(self, user, repo, message, nodes, parent_commit=None,
667 def create_nodes(self, user, repo, message, nodes, parent_commit=None,
664 author=None, trigger_push_hook=True):
668 author=None, trigger_push_hook=True):
665 """
669 """
666 Commits given multiple nodes into repo
670 Commits given multiple nodes into repo
667
671
668 :param user: RhodeCode User object or user_id, the commiter
672 :param user: RhodeCode User object or user_id, the commiter
669 :param repo: RhodeCode Repository object
673 :param repo: RhodeCode Repository object
670 :param message: commit message
674 :param message: commit message
671 :param nodes: mapping {filename:{'content':content},...}
675 :param nodes: mapping {filename:{'content':content},...}
672 :param parent_commit: parent commit, can be empty than it's
676 :param parent_commit: parent commit, can be empty than it's
673 initial commit
677 initial commit
674 :param author: author of commit, cna be different that commiter
678 :param author: author of commit, cna be different that commiter
675 only for git
679 only for git
676 :param trigger_push_hook: trigger push hooks
680 :param trigger_push_hook: trigger push hooks
677
681
678 :returns: new commited commit
682 :returns: new commited commit
679 """
683 """
680
684
681 user = self._get_user(user)
685 user = self._get_user(user)
682 scm_instance = repo.scm_instance(cache=False)
686 scm_instance = repo.scm_instance(cache=False)
683
687
684 processed_nodes = []
688 processed_nodes = []
685 for f_path in nodes:
689 for f_path in nodes:
686 f_path = self._sanitize_path(f_path)
690 f_path = self._sanitize_path(f_path)
687 content = nodes[f_path]['content']
691 content = nodes[f_path]['content']
688 f_path = safe_str(f_path)
692 f_path = safe_str(f_path)
689 # decoding here will force that we have proper encoded values
693 # decoding here will force that we have proper encoded values
690 # in any other case this will throw exceptions and deny commit
694 # in any other case this will throw exceptions and deny commit
691 if isinstance(content, (basestring,)):
695 if isinstance(content, (basestring,)):
692 content = safe_str(content)
696 content = safe_str(content)
693 elif isinstance(content, (file, cStringIO.OutputType,)):
697 elif isinstance(content, (file, cStringIO.OutputType,)):
694 content = content.read()
698 content = content.read()
695 else:
699 else:
696 raise Exception('Content is of unrecognized type %s' % (
700 raise Exception('Content is of unrecognized type %s' % (
697 type(content)
701 type(content)
698 ))
702 ))
699 processed_nodes.append((f_path, content))
703 processed_nodes.append((f_path, content))
700
704
701 message = safe_unicode(message)
705 message = safe_unicode(message)
702 commiter = user.full_contact
706 commiter = user.full_contact
703 author = safe_unicode(author) if author else commiter
707 author = safe_unicode(author) if author else commiter
704
708
705 imc = scm_instance.in_memory_commit
709 imc = scm_instance.in_memory_commit
706
710
707 if not parent_commit:
711 if not parent_commit:
708 parent_commit = EmptyCommit(alias=scm_instance.alias)
712 parent_commit = EmptyCommit(alias=scm_instance.alias)
709
713
710 if isinstance(parent_commit, EmptyCommit):
714 if isinstance(parent_commit, EmptyCommit):
711 # EmptyCommit means we we're editing empty repository
715 # EmptyCommit means we we're editing empty repository
712 parents = None
716 parents = None
713 else:
717 else:
714 parents = [parent_commit]
718 parents = [parent_commit]
715 # add multiple nodes
719 # add multiple nodes
716 for path, content in processed_nodes:
720 for path, content in processed_nodes:
717 imc.add(FileNode(path, content=content))
721 imc.add(FileNode(path, content=content))
718 # TODO: handle pre push scenario
722 # TODO: handle pre push scenario
719 tip = imc.commit(message=message,
723 tip = imc.commit(message=message,
720 author=author,
724 author=author,
721 parents=parents,
725 parents=parents,
722 branch=parent_commit.branch)
726 branch=parent_commit.branch)
723
727
724 self.mark_for_invalidation(repo.repo_name)
728 self.mark_for_invalidation(repo.repo_name)
725 if trigger_push_hook:
729 if trigger_push_hook:
726 hooks_utils.trigger_post_push_hook(
730 hooks_utils.trigger_post_push_hook(
727 username=user.username, action='push_local',
731 username=user.username, action='push_local',
728 repo_name=repo.repo_name, repo_alias=scm_instance.alias,
732 repo_name=repo.repo_name, repo_alias=scm_instance.alias,
729 hook_type='post_push',
733 hook_type='post_push',
730 commit_ids=[tip.raw_id])
734 commit_ids=[tip.raw_id])
731 return tip
735 return tip
732
736
733 def update_nodes(self, user, repo, message, nodes, parent_commit=None,
737 def update_nodes(self, user, repo, message, nodes, parent_commit=None,
734 author=None, trigger_push_hook=True):
738 author=None, trigger_push_hook=True):
735 user = self._get_user(user)
739 user = self._get_user(user)
736 scm_instance = repo.scm_instance(cache=False)
740 scm_instance = repo.scm_instance(cache=False)
737
741
738 message = safe_unicode(message)
742 message = safe_unicode(message)
739 commiter = user.full_contact
743 commiter = user.full_contact
740 author = safe_unicode(author) if author else commiter
744 author = safe_unicode(author) if author else commiter
741
745
742 imc = scm_instance.in_memory_commit
746 imc = scm_instance.in_memory_commit
743
747
744 if not parent_commit:
748 if not parent_commit:
745 parent_commit = EmptyCommit(alias=scm_instance.alias)
749 parent_commit = EmptyCommit(alias=scm_instance.alias)
746
750
747 if isinstance(parent_commit, EmptyCommit):
751 if isinstance(parent_commit, EmptyCommit):
748 # EmptyCommit means we we're editing empty repository
752 # EmptyCommit means we we're editing empty repository
749 parents = None
753 parents = None
750 else:
754 else:
751 parents = [parent_commit]
755 parents = [parent_commit]
752
756
753 # add multiple nodes
757 # add multiple nodes
754 for _filename, data in nodes.items():
758 for _filename, data in nodes.items():
755 # new filename, can be renamed from the old one, also sanitaze
759 # new filename, can be renamed from the old one, also sanitaze
756 # the path for any hack around relative paths like ../../ etc.
760 # the path for any hack around relative paths like ../../ etc.
757 filename = self._sanitize_path(data['filename'])
761 filename = self._sanitize_path(data['filename'])
758 old_filename = self._sanitize_path(_filename)
762 old_filename = self._sanitize_path(_filename)
759 content = data['content']
763 content = data['content']
760 file_mode = data.get('mode')
764 file_mode = data.get('mode')
761 filenode = FileNode(old_filename, content=content, mode=file_mode)
765 filenode = FileNode(old_filename, content=content, mode=file_mode)
762 op = data['op']
766 op = data['op']
763 if op == 'add':
767 if op == 'add':
764 imc.add(filenode)
768 imc.add(filenode)
765 elif op == 'del':
769 elif op == 'del':
766 imc.remove(filenode)
770 imc.remove(filenode)
767 elif op == 'mod':
771 elif op == 'mod':
768 if filename != old_filename:
772 if filename != old_filename:
769 # TODO: handle renames more efficient, needs vcs lib changes
773 # TODO: handle renames more efficient, needs vcs lib changes
770 imc.remove(filenode)
774 imc.remove(filenode)
771 imc.add(FileNode(filename, content=content, mode=file_mode))
775 imc.add(FileNode(filename, content=content, mode=file_mode))
772 else:
776 else:
773 imc.change(filenode)
777 imc.change(filenode)
774
778
775 try:
779 try:
776 # TODO: handle pre push scenario commit changes
780 # TODO: handle pre push scenario commit changes
777 tip = imc.commit(message=message,
781 tip = imc.commit(message=message,
778 author=author,
782 author=author,
779 parents=parents,
783 parents=parents,
780 branch=parent_commit.branch)
784 branch=parent_commit.branch)
781 except NodeNotChangedError:
785 except NodeNotChangedError:
782 raise
786 raise
783 except Exception as e:
787 except Exception as e:
784 log.exception("Unexpected exception during call to imc.commit")
788 log.exception("Unexpected exception during call to imc.commit")
785 raise IMCCommitError(str(e))
789 raise IMCCommitError(str(e))
786 finally:
790 finally:
787 # always clear caches, if commit fails we want fresh object also
791 # always clear caches, if commit fails we want fresh object also
788 self.mark_for_invalidation(repo.repo_name)
792 self.mark_for_invalidation(repo.repo_name)
789
793
790 if trigger_push_hook:
794 if trigger_push_hook:
791 hooks_utils.trigger_post_push_hook(
795 hooks_utils.trigger_post_push_hook(
792 username=user.username, action='push_local', hook_type='post_push',
796 username=user.username, action='push_local', hook_type='post_push',
793 repo_name=repo.repo_name, repo_alias=scm_instance.alias,
797 repo_name=repo.repo_name, repo_alias=scm_instance.alias,
794 commit_ids=[tip.raw_id])
798 commit_ids=[tip.raw_id])
795
799
796 def delete_nodes(self, user, repo, message, nodes, parent_commit=None,
800 def delete_nodes(self, user, repo, message, nodes, parent_commit=None,
797 author=None, trigger_push_hook=True):
801 author=None, trigger_push_hook=True):
798 """
802 """
799 Deletes given multiple nodes into `repo`
803 Deletes given multiple nodes into `repo`
800
804
801 :param user: RhodeCode User object or user_id, the committer
805 :param user: RhodeCode User object or user_id, the committer
802 :param repo: RhodeCode Repository object
806 :param repo: RhodeCode Repository object
803 :param message: commit message
807 :param message: commit message
804 :param nodes: mapping {filename:{'content':content},...}
808 :param nodes: mapping {filename:{'content':content},...}
805 :param parent_commit: parent commit, can be empty than it's initial
809 :param parent_commit: parent commit, can be empty than it's initial
806 commit
810 commit
807 :param author: author of commit, cna be different that commiter only
811 :param author: author of commit, cna be different that commiter only
808 for git
812 for git
809 :param trigger_push_hook: trigger push hooks
813 :param trigger_push_hook: trigger push hooks
810
814
811 :returns: new commit after deletion
815 :returns: new commit after deletion
812 """
816 """
813
817
814 user = self._get_user(user)
818 user = self._get_user(user)
815 scm_instance = repo.scm_instance(cache=False)
819 scm_instance = repo.scm_instance(cache=False)
816
820
817 processed_nodes = []
821 processed_nodes = []
818 for f_path in nodes:
822 for f_path in nodes:
819 f_path = self._sanitize_path(f_path)
823 f_path = self._sanitize_path(f_path)
820 # content can be empty but for compatabilty it allows same dicts
824 # content can be empty but for compatabilty it allows same dicts
821 # structure as add_nodes
825 # structure as add_nodes
822 content = nodes[f_path].get('content')
826 content = nodes[f_path].get('content')
823 processed_nodes.append((f_path, content))
827 processed_nodes.append((f_path, content))
824
828
825 message = safe_unicode(message)
829 message = safe_unicode(message)
826 commiter = user.full_contact
830 commiter = user.full_contact
827 author = safe_unicode(author) if author else commiter
831 author = safe_unicode(author) if author else commiter
828
832
829 imc = scm_instance.in_memory_commit
833 imc = scm_instance.in_memory_commit
830
834
831 if not parent_commit:
835 if not parent_commit:
832 parent_commit = EmptyCommit(alias=scm_instance.alias)
836 parent_commit = EmptyCommit(alias=scm_instance.alias)
833
837
834 if isinstance(parent_commit, EmptyCommit):
838 if isinstance(parent_commit, EmptyCommit):
835 # EmptyCommit means we we're editing empty repository
839 # EmptyCommit means we we're editing empty repository
836 parents = None
840 parents = None
837 else:
841 else:
838 parents = [parent_commit]
842 parents = [parent_commit]
839 # add multiple nodes
843 # add multiple nodes
840 for path, content in processed_nodes:
844 for path, content in processed_nodes:
841 imc.remove(FileNode(path, content=content))
845 imc.remove(FileNode(path, content=content))
842
846
843 # TODO: handle pre push scenario
847 # TODO: handle pre push scenario
844 tip = imc.commit(message=message,
848 tip = imc.commit(message=message,
845 author=author,
849 author=author,
846 parents=parents,
850 parents=parents,
847 branch=parent_commit.branch)
851 branch=parent_commit.branch)
848
852
849 self.mark_for_invalidation(repo.repo_name)
853 self.mark_for_invalidation(repo.repo_name)
850 if trigger_push_hook:
854 if trigger_push_hook:
851 hooks_utils.trigger_post_push_hook(
855 hooks_utils.trigger_post_push_hook(
852 username=user.username, action='push_local', hook_type='post_push',
856 username=user.username, action='push_local', hook_type='post_push',
853 repo_name=repo.repo_name, repo_alias=scm_instance.alias,
857 repo_name=repo.repo_name, repo_alias=scm_instance.alias,
854 commit_ids=[tip.raw_id])
858 commit_ids=[tip.raw_id])
855 return tip
859 return tip
856
860
857 def strip(self, repo, commit_id, branch):
861 def strip(self, repo, commit_id, branch):
858 scm_instance = repo.scm_instance(cache=False)
862 scm_instance = repo.scm_instance(cache=False)
859 scm_instance.config.clear_section('hooks')
863 scm_instance.config.clear_section('hooks')
860 scm_instance.strip(commit_id, branch)
864 scm_instance.strip(commit_id, branch)
861 self.mark_for_invalidation(repo.repo_name)
865 self.mark_for_invalidation(repo.repo_name)
862
866
863 def get_unread_journal(self):
867 def get_unread_journal(self):
864 return self.sa.query(UserLog).count()
868 return self.sa.query(UserLog).count()
865
869
866 def get_repo_landing_revs(self, translator, repo=None):
870 def get_repo_landing_revs(self, translator, repo=None):
867 """
871 """
868 Generates select option with tags branches and bookmarks (for hg only)
872 Generates select option with tags branches and bookmarks (for hg only)
869 grouped by type
873 grouped by type
870
874
871 :param repo:
875 :param repo:
872 """
876 """
873 _ = translator
877 _ = translator
874 repo = self._get_repo(repo)
878 repo = self._get_repo(repo)
875
879
876 hist_l = [
880 hist_l = [
877 ['rev:tip', _('latest tip')]
881 ['rev:tip', _('latest tip')]
878 ]
882 ]
879 choices = [
883 choices = [
880 'rev:tip'
884 'rev:tip'
881 ]
885 ]
882
886
883 if not repo:
887 if not repo:
884 return choices, hist_l
888 return choices, hist_l
885
889
886 repo = repo.scm_instance()
890 repo = repo.scm_instance()
887
891
888 branches_group = (
892 branches_group = (
889 [(u'branch:%s' % safe_unicode(b), safe_unicode(b))
893 [(u'branch:%s' % safe_unicode(b), safe_unicode(b))
890 for b in repo.branches],
894 for b in repo.branches],
891 _("Branches"))
895 _("Branches"))
892 hist_l.append(branches_group)
896 hist_l.append(branches_group)
893 choices.extend([x[0] for x in branches_group[0]])
897 choices.extend([x[0] for x in branches_group[0]])
894
898
895 if repo.alias == 'hg':
899 if repo.alias == 'hg':
896 bookmarks_group = (
900 bookmarks_group = (
897 [(u'book:%s' % safe_unicode(b), safe_unicode(b))
901 [(u'book:%s' % safe_unicode(b), safe_unicode(b))
898 for b in repo.bookmarks],
902 for b in repo.bookmarks],
899 _("Bookmarks"))
903 _("Bookmarks"))
900 hist_l.append(bookmarks_group)
904 hist_l.append(bookmarks_group)
901 choices.extend([x[0] for x in bookmarks_group[0]])
905 choices.extend([x[0] for x in bookmarks_group[0]])
902
906
903 tags_group = (
907 tags_group = (
904 [(u'tag:%s' % safe_unicode(t), safe_unicode(t))
908 [(u'tag:%s' % safe_unicode(t), safe_unicode(t))
905 for t in repo.tags],
909 for t in repo.tags],
906 _("Tags"))
910 _("Tags"))
907 hist_l.append(tags_group)
911 hist_l.append(tags_group)
908 choices.extend([x[0] for x in tags_group[0]])
912 choices.extend([x[0] for x in tags_group[0]])
909
913
910 return choices, hist_l
914 return choices, hist_l
911
915
912 def get_server_info(self, environ=None):
916 def get_server_info(self, environ=None):
913 server_info = get_system_info(environ)
917 server_info = get_system_info(environ)
914 return server_info
918 return server_info
General Comments 0
You need to be logged in to leave comments. Login now