##// END OF EJS Templates
Switched handling of RhodeCode extra params in consistent way...
marcink -
r3577:238486bb beta
parent child Browse files
Show More
@@ -26,6 +26,7 b' import os'
26 26 import sys
27 27 import time
28 28 import binascii
29 import traceback
29 30 from inspect import isfunction
30 31
31 32 from mercurial.scmutil import revrange
@@ -36,7 +37,7 b' from rhodecode.lib.utils import action_l'
36 37 from rhodecode.lib.vcs.backends.base import EmptyChangeset
37 38 from rhodecode.lib.compat import json
38 39 from rhodecode.lib.exceptions import HTTPLockedRC
39 from rhodecode.lib.utils2 import safe_str
40 from rhodecode.lib.utils2 import safe_str, _extract_extras
40 41 from rhodecode.model.db import Repository, User
41 42
42 43
@@ -91,31 +92,14 b' def repo_size(ui, repo, hooktype=None, *'
91 92 def pre_push(ui, repo, **kwargs):
92 93 # pre push function, currently used to ban pushing when
93 94 # repository is locked
94 try:
95 rc_extras = json.loads(os.environ.get('RC_SCM_DATA', "{}"))
96 except:
97 rc_extras = {}
98 extras = dict(repo.ui.configitems('rhodecode_extras'))
95 ex = _extract_extras()
99 96
100 if 'username' in extras:
101 username = extras['username']
102 repository = extras['repository']
103 scm = extras['scm']
104 locked_by = extras['locked_by']
105 elif 'username' in rc_extras:
106 username = rc_extras['username']
107 repository = rc_extras['repository']
108 scm = rc_extras['scm']
109 locked_by = rc_extras['locked_by']
110 else:
111 raise Exception('Missing data in repo.ui and os.environ')
112
113 usr = User.get_by_username(username)
114 if locked_by[0] and usr.user_id != int(locked_by[0]):
115 locked_by = User.get(locked_by[0]).username
97 usr = User.get_by_username(ex.username)
98 if ex.locked_by[0] and usr.user_id != int(ex.locked_by[0]):
99 locked_by = User.get(ex.locked_by[0]).username
116 100 # this exception is interpreted in git/hg middlewares and based
117 101 # on that proper return code is server to client
118 _http_ret = HTTPLockedRC(repository, locked_by)
102 _http_ret = HTTPLockedRC(ex.repository, locked_by)
119 103 if str(_http_ret.code).startswith('2'):
120 104 #2xx Codes don't raise exceptions
121 105 sys.stdout.write(_http_ret.title)
@@ -126,29 +110,12 b' def pre_push(ui, repo, **kwargs):'
126 110 def pre_pull(ui, repo, **kwargs):
127 111 # pre push function, currently used to ban pushing when
128 112 # repository is locked
129 try:
130 rc_extras = json.loads(os.environ.get('RC_SCM_DATA', "{}"))
131 except:
132 rc_extras = {}
133 extras = dict(repo.ui.configitems('rhodecode_extras'))
134 if 'username' in extras:
135 username = extras['username']
136 repository = extras['repository']
137 scm = extras['scm']
138 locked_by = extras['locked_by']
139 elif 'username' in rc_extras:
140 username = rc_extras['username']
141 repository = rc_extras['repository']
142 scm = rc_extras['scm']
143 locked_by = rc_extras['locked_by']
144 else:
145 raise Exception('Missing data in repo.ui and os.environ')
146
147 if locked_by[0]:
148 locked_by = User.get(locked_by[0]).username
113 ex = _extract_extras()
114 if ex.locked_by[0]:
115 locked_by = User.get(ex.locked_by[0]).username
149 116 # this exception is interpreted in git/hg middlewares and based
150 117 # on that proper return code is server to client
151 _http_ret = HTTPLockedRC(repository, locked_by)
118 _http_ret = HTTPLockedRC(ex.repository, locked_by)
152 119 if str(_http_ret.code).startswith('2'):
153 120 #2xx Codes don't raise exceptions
154 121 sys.stdout.write(_http_ret.title)
@@ -163,47 +130,27 b' def log_pull_action(ui, repo, **kwargs):'
163 130 :param ui:
164 131 :param repo:
165 132 """
166 try:
167 rc_extras = json.loads(os.environ.get('RC_SCM_DATA', "{}"))
168 except:
169 rc_extras = {}
170 extras = dict(repo.ui.configitems('rhodecode_extras'))
171 if 'username' in extras:
172 username = extras['username']
173 repository = extras['repository']
174 scm = extras['scm']
175 make_lock = extras['make_lock']
176 locked_by = extras['locked_by']
177 ip = extras['ip']
178 elif 'username' in rc_extras:
179 username = rc_extras['username']
180 repository = rc_extras['repository']
181 scm = rc_extras['scm']
182 make_lock = rc_extras['make_lock']
183 locked_by = rc_extras['locked_by']
184 ip = rc_extras['ip']
185 else:
186 raise Exception('Missing data in repo.ui and os.environ')
187 user = User.get_by_username(username)
133 ex = _extract_extras()
134
135 user = User.get_by_username(ex.username)
188 136 action = 'pull'
189 action_logger(user, action, repository, ip, commit=True)
137 action_logger(user, action, ex.repository, ex.ip, commit=True)
190 138 # extension hook call
191 139 from rhodecode import EXTENSIONS
192 140 callback = getattr(EXTENSIONS, 'PULL_HOOK', None)
193
194 141 if isfunction(callback):
195 142 kw = {}
196 kw.update(extras)
143 kw.update(ex)
197 144 callback(**kw)
198 145
199 if make_lock is True:
200 Repository.lock(Repository.get_by_repo_name(repository), user.user_id)
146 if ex.make_lock is True:
147 Repository.lock(Repository.get_by_repo_name(ex.repository), user.user_id)
201 148 #msg = 'Made lock on repo `%s`' % repository
202 149 #sys.stdout.write(msg)
203 150
204 if locked_by[0]:
205 locked_by = User.get(locked_by[0]).username
206 _http_ret = HTTPLockedRC(repository, locked_by)
151 if ex.locked_by[0]:
152 locked_by = User.get(ex.locked_by[0]).username
153 _http_ret = HTTPLockedRC(ex.repository, locked_by)
207 154 if str(_http_ret.code).startswith('2'):
208 155 #2xx Codes don't raise exceptions
209 156 sys.stdout.write(_http_ret.title)
@@ -218,32 +165,11 b' def log_push_action(ui, repo, **kwargs):'
218 165 :param repo: repo object containing the `ui` object
219 166 """
220 167
221 try:
222 rc_extras = json.loads(os.environ.get('RC_SCM_DATA', "{}"))
223 except:
224 rc_extras = {}
168 ex = _extract_extras()
225 169
226 extras = dict(repo.ui.configitems('rhodecode_extras'))
227 if 'username' in extras:
228 username = extras['username']
229 repository = extras['repository']
230 scm = extras['scm']
231 make_lock = extras['make_lock']
232 locked_by = extras['locked_by']
233 action = extras['action']
234 elif 'username' in rc_extras:
235 username = rc_extras['username']
236 repository = rc_extras['repository']
237 scm = rc_extras['scm']
238 make_lock = rc_extras['make_lock']
239 locked_by = rc_extras['locked_by']
240 action = extras['action']
241 else:
242 raise Exception('Missing data in repo.ui and os.environ')
170 action = ex.action + ':%s'
243 171
244 action = action + ':%s'
245
246 if scm == 'hg':
172 if ex.scm == 'hg':
247 173 node = kwargs['node']
248 174
249 175 def get_revs(repo, rev_opt):
@@ -259,31 +185,31 b' def log_push_action(ui, repo, **kwargs):'
259 185 stop, start = get_revs(repo, [node + ':'])
260 186 h = binascii.hexlify
261 187 revs = [h(repo[r].node()) for r in xrange(start, stop + 1)]
262 elif scm == 'git':
188 elif ex.scm == 'git':
263 189 revs = kwargs.get('_git_revs', [])
264 190 if '_git_revs' in kwargs:
265 191 kwargs.pop('_git_revs')
266 192
267 193 action = action % ','.join(revs)
268 194
269 action_logger(username, action, repository, extras['ip'], commit=True)
195 action_logger(ex.username, action, ex.repository, ex.ip, commit=True)
270 196
271 197 # extension hook call
272 198 from rhodecode import EXTENSIONS
273 199 callback = getattr(EXTENSIONS, 'PUSH_HOOK', None)
274 200 if isfunction(callback):
275 201 kw = {'pushed_revs': revs}
276 kw.update(extras)
202 kw.update(ex)
277 203 callback(**kw)
278 204
279 if make_lock is False:
280 Repository.unlock(Repository.get_by_repo_name(repository))
281 msg = 'Released lock on repo `%s`\n' % repository
205 if ex.make_lock is False:
206 Repository.unlock(Repository.get_by_repo_name(ex.repository))
207 msg = 'Released lock on repo `%s`\n' % ex.repository
282 208 sys.stdout.write(msg)
283 209
284 if locked_by[0]:
285 locked_by = User.get(locked_by[0]).username
286 _http_ret = HTTPLockedRC(repository, locked_by)
210 if ex.locked_by[0]:
211 locked_by = User.get(ex.locked_by[0]).username
212 _http_ret = HTTPLockedRC(ex.repository, locked_by)
287 213 if str(_http_ret.code).startswith('2'):
288 214 #2xx Codes don't raise exceptions
289 215 sys.stdout.write(_http_ret.title)
@@ -121,8 +121,6 b' class GitRepository(object):'
121 121
122 122 try:
123 123 gitenv = os.environ
124 from rhodecode.lib.compat import json
125 gitenv['RHODECODE_EXTRAS'] = json.dumps(self.extras)
126 124 # forget all configs
127 125 gitenv['GIT_CONFIG_NOGLOBAL'] = '1'
128 126 opts = dict(
@@ -79,7 +79,8 b' from paste.httpheaders import REMOTE_USE'
79 79 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError, \
80 80 HTTPBadRequest, HTTPNotAcceptable
81 81
82 from rhodecode.lib.utils2 import safe_str, fix_PATH, get_server_url
82 from rhodecode.lib.utils2 import safe_str, fix_PATH, get_server_url,\
83 _set_extras
83 84 from rhodecode.lib.base import BaseVCSController
84 85 from rhodecode.lib.auth import get_container_username
85 86 from rhodecode.lib.utils import is_valid_repo, make_ui
@@ -333,10 +334,4 b' class SimpleGit(BaseVCSController):'
333 334 :param extras: dict with extra params to put into baseui
334 335 """
335 336
336 # make our hgweb quiet so it doesn't print output
337 baseui.setconfig('ui', 'quiet', 'true')
338
339 #inject some additional parameters that will be available in ui
340 #for hooks
341 for k, v in extras.items():
342 baseui.setconfig('rhodecode_extras', k, v)
337 _set_extras(extras)
@@ -35,7 +35,8 b' from paste.httpheaders import REMOTE_USE'
35 35 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError, \
36 36 HTTPBadRequest, HTTPNotAcceptable
37 37
38 from rhodecode.lib.utils2 import safe_str, fix_PATH, get_server_url
38 from rhodecode.lib.utils2 import safe_str, fix_PATH, get_server_url,\
39 _set_extras
39 40 from rhodecode.lib.base import BaseVCSController
40 41 from rhodecode.lib.auth import get_container_username
41 42 from rhodecode.lib.utils import make_ui, is_valid_repo, ui_sections
@@ -276,11 +277,6 b' class SimpleHg(BaseVCSController):'
276 277 # make our hgweb quiet so it doesn't print output
277 278 baseui.setconfig('ui', 'quiet', 'true')
278 279
279 #inject some additional parameters that will be available in ui
280 #for hooks
281 for k, v in extras.items():
282 baseui.setconfig('rhodecode_extras', k, v)
283
284 280 repoui = make_ui('file', hgrc, False)
285 281
286 282 if repoui:
@@ -288,3 +284,4 b' class SimpleHg(BaseVCSController):'
288 284 for section in ui_sections:
289 285 for k, v in repoui.configitems(section):
290 286 baseui.setconfig(section, k, v)
287 _set_extras(extras)
@@ -23,13 +23,17 b''
23 23 # You should have received a copy of the GNU General Public License
24 24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 25
26 import os
26 27 import re
28 import sys
27 29 import time
28 30 import datetime
31 import traceback
29 32 import webob
30 33
31 34 from pylons.i18n.translation import _, ungettext
32 35 from rhodecode.lib.vcs.utils.lazy import LazyProperty
36 from rhodecode.lib.compat import json
33 37
34 38
35 39 def __get_lem():
@@ -552,7 +556,6 b' def fix_PATH(os_=None):'
552 556 Get current active python path, and append it to PATH variable to fix issues
553 557 of subprocess calls and different python versions
554 558 """
555 import sys
556 559 if os_ is None:
557 560 import os
558 561 else:
@@ -578,3 +581,29 b' def obfuscate_url_pw(engine):'
578 581 def get_server_url(environ):
579 582 req = webob.Request(environ)
580 583 return req.host_url + req.script_name
584
585
586 def _extract_extras():
587 """
588 Extracts the rc extras data from os.environ, and wraps it into named
589 AttributeDict object
590 """
591 try:
592 rc_extras = json.loads(os.environ['RC_SCM_DATA'])
593 except:
594 print os.environ
595 print >> sys.stderr, traceback.format_exc()
596 rc_extras = {}
597
598 try:
599 for k in ['username', 'repository', 'locked_by', 'scm', 'make_lock',
600 'action', 'ip']:
601 rc_extras[k]
602 except KeyError, e:
603 raise Exception('Missing key %s in os.environ %s' % (e, rc_extras))
604
605 return AttributeDict(rc_extras)
606
607
608 def _set_extras(extras):
609 os.environ['RC_SCM_DATA'] = json.dumps(extras)
@@ -311,27 +311,6 b' class BaseRepository(object):'
311 311 """
312 312 raise NotImplementedError
313 313
314 def inject_ui(self, **extras):
315 """
316 Injects extra parameters into UI object of this repo
317 """
318 required_extras = [
319 'ip',
320 'username',
321 'action',
322 'repository',
323 'scm',
324 'config',
325 'server_url',
326 'make_lock',
327 'locked_by',
328 ]
329 for req in required_extras:
330 if req not in extras:
331 raise AttributeError('Missing attribute %s in extras' % (req))
332 for k, v in extras.items():
333 self._repo.ui.setconfig('rhodecode_extras', k, v)
334
335 314
336 315 class BaseChangeset(object):
337 316 """
@@ -66,14 +66,7 b' class GitRepository(BaseRepository):'
66 66
67 67 @ThreadLocalLazyProperty
68 68 def _repo(self):
69 repo = Repo(self.path)
70 # patch the instance of GitRepo with an "FAKE" ui object to add
71 # compatibility layer with Mercurial
72 if not hasattr(repo, 'ui'):
73 from mercurial.ui import ui
74 baseui = ui()
75 setattr(repo, 'ui', baseui)
76 return repo
69 return Repo(self.path)
77 70
78 71 @property
79 72 def head(self):
@@ -47,7 +47,7 b' from rhodecode.lib.vcs.utils.lazy import'
47 47 from rhodecode.lib.vcs.backends.base import EmptyChangeset
48 48
49 49 from rhodecode.lib.utils2 import str2bool, safe_str, get_changeset_safe, \
50 safe_unicode, remove_suffix, remove_prefix, time_to_datetime
50 safe_unicode, remove_suffix, remove_prefix, time_to_datetime, _set_extras
51 51 from rhodecode.lib.compat import json
52 52 from rhodecode.lib.caching_query import FromCache
53 53
@@ -937,10 +937,6 b' class Repository(Base, BaseModel):'
937 937 return make_ui('db', clear_session=False)
938 938
939 939 @classmethod
940 def inject_ui(cls, repo, extras={}):
941 repo.inject_ui(extras)
942
943 @classmethod
944 940 def is_valid(cls, repo_name):
945 941 """
946 942 returns True if given repo name is a valid filesystem repository
@@ -44,7 +44,8 b' from rhodecode.lib.vcs.backends.base imp'
44 44
45 45 from rhodecode import BACKENDS
46 46 from rhodecode.lib import helpers as h
47 from rhodecode.lib.utils2 import safe_str, safe_unicode, get_server_url
47 from rhodecode.lib.utils2 import safe_str, safe_unicode, get_server_url,\
48 _set_extras
48 49 from rhodecode.lib.auth import HasRepoPermissionAny, HasReposGroupPermissionAny
49 50 from rhodecode.lib.utils import get_filesystem_repos, make_ui, \
50 51 action_logger, REMOVED_REPO_PAT
@@ -437,7 +438,7 b' class ScmModel(BaseModel):'
437 438 'locked_by': [None, None]
438 439 }
439 440 _scm_repo = repo._repo
440 repo.inject_ui(**extras)
441 _set_extras(extras)
441 442 if repo.alias == 'hg':
442 443 log_push_action(_scm_repo.ui, _scm_repo, node=revisions[0])
443 444 elif repo.alias == 'git':
General Comments 0
You need to be logged in to leave comments. Login now