##// END OF EJS Templates
py3: drop the last uses of safe_str - they are no longer relevant when we don't have a separate unicode type
Mads Kiilerich -
r8076:e51ad2cd default
parent child Browse files
Show More
@@ -28,7 +28,7 b' import click'
28
28
29 import kallithea.bin.kallithea_cli_base as cli_base
29 import kallithea.bin.kallithea_cli_base as cli_base
30 from kallithea.lib.utils import REMOVED_REPO_PAT, repo2db_mapper
30 from kallithea.lib.utils import REMOVED_REPO_PAT, repo2db_mapper
31 from kallithea.lib.utils2 import ask_ok, safe_str
31 from kallithea.lib.utils2 import ask_ok
32 from kallithea.model.db import Repository, Ui
32 from kallithea.model.db import Repository, Ui
33 from kallithea.model.meta import Session
33 from kallithea.model.meta import Session
34 from kallithea.model.scm import ScmModel
34 from kallithea.model.scm import ScmModel
@@ -127,7 +127,7 b' def repo_purge_deleted(ask, older_than):'
127
127
128 repos_location = Ui.get_repos_location()
128 repos_location = Ui.get_repos_location()
129 to_remove = []
129 to_remove = []
130 for dn_, dirs, f in os.walk(safe_str(repos_location)):
130 for dn_, dirs, f in os.walk(repos_location):
131 alldirs = list(dirs)
131 alldirs = list(dirs)
132 del dirs[:]
132 del dirs[:]
133 if ('.hg' in alldirs or
133 if ('.hg' in alldirs or
@@ -175,9 +175,8 b' def repo_purge_deleted(ask, older_than):'
175 remove = True
175 remove = True
176 else:
176 else:
177 remove = ask_ok('The following repositories will be removed completely:\n%s\n'
177 remove = ask_ok('The following repositories will be removed completely:\n%s\n'
178 'Do you want to proceed? [y/n] '
178 'Do you want to proceed? [y/n] ' %
179 % '\n'.join(['%s deleted on %s' % (safe_str(x[0]), safe_str(x[1]))
179 '\n'.join('%s deleted on %s' % (path, date_) for path, date_ in to_remove))
180 for x in to_remove]))
181
180
182 if remove:
181 if remove:
183 for path, date_ in to_remove:
182 for path, date_ in to_remove:
@@ -39,7 +39,7 b' from kallithea.lib import ext_json'
39 from kallithea.lib.auth import AuthUser
39 from kallithea.lib.auth import AuthUser
40 from kallithea.lib.base import _get_ip_addr as _get_ip
40 from kallithea.lib.base import _get_ip_addr as _get_ip
41 from kallithea.lib.base import get_path_info
41 from kallithea.lib.base import get_path_info
42 from kallithea.lib.utils2 import ascii_bytes, safe_str
42 from kallithea.lib.utils2 import ascii_bytes
43 from kallithea.model.db import User
43 from kallithea.model.db import User
44
44
45
45
@@ -53,7 +53,7 b' class JSONRPCError(BaseException):'
53 super(JSONRPCError, self).__init__()
53 super(JSONRPCError, self).__init__()
54
54
55 def __str__(self):
55 def __str__(self):
56 return safe_str(self.message)
56 return self.message
57
57
58
58
59 class JSONRPCErrorResponse(Response, HTTPException):
59 class JSONRPCErrorResponse(Response, HTTPException):
@@ -43,7 +43,7 b' from kallithea.lib import helpers as h'
43 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
43 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
44 from kallithea.lib.base import BaseRepoController, render
44 from kallithea.lib.base import BaseRepoController, render
45 from kallithea.lib.graphmod import graph_data
45 from kallithea.lib.graphmod import graph_data
46 from kallithea.lib.utils2 import ascii_bytes, ascii_str, safe_bytes, safe_int, safe_str
46 from kallithea.lib.utils2 import ascii_bytes, ascii_str, safe_bytes, safe_int
47 from kallithea.model.db import Repository
47 from kallithea.model.db import Repository
48
48
49
49
@@ -135,10 +135,10 b' class CompareController(BaseRepoControll'
135 from dulwich.client import SubprocessGitClient
135 from dulwich.client import SubprocessGitClient
136
136
137 gitrepo = Repo(org_repo.path)
137 gitrepo = Repo(org_repo.path)
138 SubprocessGitClient(thin_packs=False).fetch(safe_str(other_repo.path), gitrepo)
138 SubprocessGitClient(thin_packs=False).fetch(other_repo.path, gitrepo)
139
139
140 gitrepo_remote = Repo(other_repo.path)
140 gitrepo_remote = Repo(other_repo.path)
141 SubprocessGitClient(thin_packs=False).fetch(safe_str(org_repo.path), gitrepo_remote)
141 SubprocessGitClient(thin_packs=False).fetch(org_repo.path, gitrepo_remote)
142
142
143 revs = [
143 revs = [
144 ascii_str(x.commit.id)
144 ascii_str(x.commit.id)
@@ -46,7 +46,7 b' from kallithea.lib.auth import HasRepoPe'
46 from kallithea.lib.base import BaseRepoController, jsonify, render
46 from kallithea.lib.base import BaseRepoController, jsonify, render
47 from kallithea.lib.exceptions import NonRelativePathError
47 from kallithea.lib.exceptions import NonRelativePathError
48 from kallithea.lib.utils import action_logger
48 from kallithea.lib.utils import action_logger
49 from kallithea.lib.utils2 import convert_line_endings, detect_mode, safe_int, safe_str, safe_unicode, str2bool
49 from kallithea.lib.utils2 import convert_line_endings, detect_mode, safe_int, safe_unicode, str2bool
50 from kallithea.lib.vcs.backends.base import EmptyChangeset
50 from kallithea.lib.vcs.backends.base import EmptyChangeset
51 from kallithea.lib.vcs.conf import settings
51 from kallithea.lib.vcs.conf import settings
52 from kallithea.lib.vcs.exceptions import (
52 from kallithea.lib.vcs.exceptions import (
@@ -232,8 +232,8 b' class FilesController(BaseRepoController'
232 cs = self.__get_cs(revision)
232 cs = self.__get_cs(revision)
233 file_node = self.__get_filenode(cs, f_path)
233 file_node = self.__get_filenode(cs, f_path)
234
234
235 response.content_disposition = 'attachment; filename=%s' % \
235 response.content_disposition = \
236 safe_str(f_path.split(Repository.url_sep())[-1])
236 'attachment; filename=%s' % f_path.split(Repository.url_sep())[-1]
237
237
238 response.content_type = file_node.mimetype
238 response.content_type = file_node.mimetype
239 return file_node.content
239 return file_node.content
@@ -277,8 +277,7 b' class FilesController(BaseRepoController'
277 mimetype, dispo = 'text/plain', 'inline'
277 mimetype, dispo = 'text/plain', 'inline'
278
278
279 if dispo == 'attachment':
279 if dispo == 'attachment':
280 dispo = 'attachment; filename=%s' % \
280 dispo = 'attachment; filename=%s' % f_path.split(os.sep)[-1]
281 safe_str(f_path.split(os.sep)[-1])
282
281
283 response.content_disposition = dispo
282 response.content_disposition = dispo
284 response.content_type = mimetype
283 response.content_type = mimetype
@@ -508,8 +507,7 b' class FilesController(BaseRepoController'
508
507
509 from kallithea import CONFIG
508 from kallithea import CONFIG
510 rev_name = cs.raw_id[:12]
509 rev_name = cs.raw_id[:12]
511 archive_name = '%s-%s%s' % (safe_str(repo_name.replace('/', '_')),
510 archive_name = '%s-%s%s' % (repo_name.replace('/', '_'), rev_name, ext)
512 safe_str(rev_name), ext)
513
511
514 archive_path = None
512 archive_path = None
515 cached_archive_path = None
513 cached_archive_path = None
@@ -41,7 +41,6 b' from kallithea.config.routing import url'
41 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
41 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
42 from kallithea.lib.base import BaseController, log_in_user, render
42 from kallithea.lib.base import BaseController, log_in_user, render
43 from kallithea.lib.exceptions import UserCreationError
43 from kallithea.lib.exceptions import UserCreationError
44 from kallithea.lib.utils2 import safe_str
45 from kallithea.model.db import Setting, User
44 from kallithea.model.db import Setting, User
46 from kallithea.model.forms import LoginForm, PasswordResetConfirmationForm, PasswordResetRequestForm, RegisterForm
45 from kallithea.model.forms import LoginForm, PasswordResetConfirmationForm, PasswordResetRequestForm, RegisterForm
47 from kallithea.model.meta import Session
46 from kallithea.model.meta import Session
@@ -68,7 +67,7 b' class LoginController(BaseController):'
68 return _re.match(came_from) is not None
67 return _re.match(came_from) is not None
69
68
70 def index(self):
69 def index(self):
71 c.came_from = safe_str(request.GET.get('came_from', ''))
70 c.came_from = request.GET.get('came_from', '')
72 if c.came_from:
71 if c.came_from:
73 if not self._validate_came_from(c.came_from):
72 if not self._validate_came_from(c.came_from):
74 log.error('Invalid came_from (not server-relative): %r', c.came_from)
73 log.error('Invalid came_from (not server-relative): %r', c.came_from)
@@ -43,7 +43,7 b' from kallithea.lib.auth import HasRepoPe'
43 from kallithea.lib.base import BaseRepoController, jsonify, render
43 from kallithea.lib.base import BaseRepoController, jsonify, render
44 from kallithea.lib.graphmod import graph_data
44 from kallithea.lib.graphmod import graph_data
45 from kallithea.lib.page import Page
45 from kallithea.lib.page import Page
46 from kallithea.lib.utils2 import ascii_bytes, safe_bytes, safe_int, safe_str
46 from kallithea.lib.utils2 import ascii_bytes, safe_bytes, safe_int
47 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError
47 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError
48 from kallithea.model.changeset_status import ChangesetStatusModel
48 from kallithea.model.changeset_status import ChangesetStatusModel
49 from kallithea.model.comment import ChangesetCommentsModel
49 from kallithea.model.comment import ChangesetCommentsModel
@@ -82,12 +82,6 b' class PullrequestsController(BaseRepoCon'
82 # list named branches that has been merged to this named branch - it should probably merge back
82 # list named branches that has been merged to this named branch - it should probably merge back
83 peers = []
83 peers = []
84
84
85 if rev:
86 rev = safe_str(rev)
87
88 if branch:
89 branch = safe_str(branch)
90
91 if branch_rev:
85 if branch_rev:
92 # a revset not restricting to merge() would be better
86 # a revset not restricting to merge() would be better
93 # (especially because it would get the branch point)
87 # (especially because it would get the branch point)
@@ -586,7 +580,7 b' class PullrequestsController(BaseRepoCon'
586 log.debug('running diff between %s and %s in %s',
580 log.debug('running diff between %s and %s in %s',
587 c.a_rev, c.cs_rev, org_scm_instance.path)
581 c.a_rev, c.cs_rev, org_scm_instance.path)
588 try:
582 try:
589 raw_diff = diffs.get_diff(org_scm_instance, rev1=safe_str(c.a_rev), rev2=safe_str(c.cs_rev),
583 raw_diff = diffs.get_diff(org_scm_instance, rev1=c.a_rev, rev2=c.cs_rev,
590 ignore_whitespace=ignore_whitespace, context=line_context)
584 ignore_whitespace=ignore_whitespace, context=line_context)
591 except ChangesetDoesNotExistError:
585 except ChangesetDoesNotExistError:
592 raw_diff = safe_bytes(_("The diff can't be shown - the PR revisions could not be found."))
586 raw_diff = safe_bytes(_("The diff can't be shown - the PR revisions could not be found."))
@@ -39,7 +39,7 b' from kallithea.lib.auth import LoginRequ'
39 from kallithea.lib.base import BaseRepoController, render
39 from kallithea.lib.base import BaseRepoController, render
40 from kallithea.lib.indexers import CHGSET_IDX_NAME, CHGSETS_SCHEMA, IDX_NAME, SCHEMA, WhooshResultWrapper
40 from kallithea.lib.indexers import CHGSET_IDX_NAME, CHGSETS_SCHEMA, IDX_NAME, SCHEMA, WhooshResultWrapper
41 from kallithea.lib.page import Page
41 from kallithea.lib.page import Page
42 from kallithea.lib.utils2 import safe_int, safe_str
42 from kallithea.lib.utils2 import safe_int
43 from kallithea.model.repo import RepoModel
43 from kallithea.model.repo import RepoModel
44
44
45
45
@@ -124,8 +124,8 b' class SearchController(BaseRepoControlle'
124 page=p,
124 page=p,
125 item_count=res_ln,
125 item_count=res_ln,
126 items_per_page=10,
126 items_per_page=10,
127 type=safe_str(c.cur_type),
127 type=c.cur_type,
128 q=safe_str(c.cur_query),
128 q=c.cur_query,
129 )
129 )
130
130
131 except QueryParserError:
131 except QueryParserError:
@@ -29,7 +29,7 b' import logging'
29
29
30 from kallithea.lib import auth_modules
30 from kallithea.lib import auth_modules
31 from kallithea.lib.compat import hybrid_property
31 from kallithea.lib.compat import hybrid_property
32 from kallithea.lib.utils2 import safe_str, str2bool
32 from kallithea.lib.utils2 import str2bool
33 from kallithea.model.db import Setting
33 from kallithea.model.db import Setting
34
34
35
35
@@ -180,7 +180,7 b' class KallitheaAuthPlugin(auth_modules.K'
180 # only way to log in is using environ
180 # only way to log in is using environ
181 username = None
181 username = None
182 if userobj:
182 if userobj:
183 username = safe_str(getattr(userobj, 'username'))
183 username = getattr(userobj, 'username')
184
184
185 if not username:
185 if not username:
186 # we don't have any objects in DB, user doesn't exist, extract
186 # we don't have any objects in DB, user doesn't exist, extract
@@ -31,7 +31,6 b' import logging'
31 from kallithea.lib import auth_modules
31 from kallithea.lib import auth_modules
32 from kallithea.lib.compat import hybrid_property
32 from kallithea.lib.compat import hybrid_property
33 from kallithea.lib.exceptions import LdapConnectionError, LdapImportError, LdapPasswordError, LdapUsernameError
33 from kallithea.lib.exceptions import LdapConnectionError, LdapImportError, LdapPasswordError, LdapUsernameError
34 from kallithea.lib.utils2 import safe_str
35
34
36
35
37 log = logging.getLogger(__name__)
36 log = logging.getLogger(__name__)
@@ -70,11 +69,11 b' class AuthLdap(object):'
70 port)
69 port)
71 for host in server.split(',')))
70 for host in server.split(',')))
72
71
73 self.LDAP_BIND_DN = safe_str(bind_dn)
72 self.LDAP_BIND_DN = bind_dn
74 self.LDAP_BIND_PASS = safe_str(bind_pass)
73 self.LDAP_BIND_PASS = bind_pass
75
74
76 self.BASE_DN = safe_str(base_dn)
75 self.BASE_DN = base_dn
77 self.LDAP_FILTER = safe_str(ldap_filter)
76 self.LDAP_FILTER = ldap_filter
78 self.SEARCH_SCOPE = getattr(ldap, 'SCOPE_%s' % search_scope)
77 self.SEARCH_SCOPE = getattr(ldap, 'SCOPE_%s' % search_scope)
79 self.attr_login = attr_login
78 self.attr_login = attr_login
80
79
@@ -139,7 +138,7 b' class AuthLdap(object):'
139
138
140 try:
139 try:
141 log.debug('Trying simple bind with %s', dn)
140 log.debug('Trying simple bind with %s', dn)
142 server.simple_bind_s(dn, safe_str(password))
141 server.simple_bind_s(dn, password)
143 results = server.search_ext_s(dn, ldap.SCOPE_BASE,
142 results = server.search_ext_s(dn, ldap.SCOPE_BASE,
144 '(objectClass=*)')
143 '(objectClass=*)')
145 if len(results) == 1:
144 if len(results) == 1:
@@ -49,7 +49,7 b' from kallithea.lib import auth_modules, '
49 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
49 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
50 from kallithea.lib.exceptions import UserCreationError
50 from kallithea.lib.exceptions import UserCreationError
51 from kallithea.lib.utils import get_repo_slug, is_valid_repo
51 from kallithea.lib.utils import get_repo_slug, is_valid_repo
52 from kallithea.lib.utils2 import AttributeDict, ascii_bytes, safe_int, safe_str, safe_unicode, set_hook_environment, str2bool
52 from kallithea.lib.utils2 import AttributeDict, ascii_bytes, safe_int, safe_unicode, set_hook_environment, str2bool
53 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
53 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
54 from kallithea.model import meta
54 from kallithea.model import meta
55 from kallithea.model.db import PullRequest, Repository, Setting, User
55 from kallithea.model.db import PullRequest, Repository, Setting, User
@@ -242,7 +242,7 b' class BaseVCSController(object):'
242
242
243 # If not authenticated by the container, running basic auth
243 # If not authenticated by the container, running basic auth
244 if not username:
244 if not username:
245 self.authenticate.realm = safe_str(self.config['realm'])
245 self.authenticate.realm = self.config['realm']
246 result = self.authenticate(environ)
246 result = self.authenticate(environ)
247 if isinstance(result, str):
247 if isinstance(result, str):
248 paste.httpheaders.AUTH_TYPE.update(environ, 'basic')
248 paste.httpheaders.AUTH_TYPE.update(environ, 'basic')
@@ -333,7 +333,7 b' class BaseVCSController(object):'
333
333
334 try:
334 try:
335 log.info('%s action on %s repo "%s" by "%s" from %s',
335 log.info('%s action on %s repo "%s" by "%s" from %s',
336 parsed_request.action, self.scm_alias, parsed_request.repo_name, safe_str(user.username), ip_addr)
336 parsed_request.action, self.scm_alias, parsed_request.repo_name, user.username, ip_addr)
337 app = self._make_app(parsed_request)
337 app = self._make_app(parsed_request)
338 return app(environ, start_response)
338 return app(environ, start_response)
339 except Exception:
339 except Exception:
@@ -24,8 +24,6 b' from sqlalchemy.orm.interfaces import Ma'
24 from sqlalchemy.orm.query import Query
24 from sqlalchemy.orm.query import Query
25 from sqlalchemy.sql import visitors
25 from sqlalchemy.sql import visitors
26
26
27 from kallithea.lib.utils2 import safe_str
28
29
27
30 class CachingQuery(Query):
28 class CachingQuery(Query):
31 """A Query subclass which optionally loads full results from a Beaker
29 """A Query subclass which optionally loads full results from a Beaker
@@ -175,7 +173,7 b' def _set_cache_parameters(query, region,'
175 "for region %r namespace %r" %
173 "for region %r namespace %r" %
176 (region, namespace)
174 (region, namespace)
177 )
175 )
178 query._cache_parameters = region, safe_str(namespace), cache_key
176 query._cache_parameters = region, namespace, cache_key
179
177
180
178
181 class FromCache(MapperOption):
179 class FromCache(MapperOption):
@@ -34,7 +34,7 b' import mercurial.scmutil'
34 from kallithea.lib import helpers as h
34 from kallithea.lib import helpers as h
35 from kallithea.lib.exceptions import UserCreationError
35 from kallithea.lib.exceptions import UserCreationError
36 from kallithea.lib.utils import action_logger, make_ui
36 from kallithea.lib.utils import action_logger, make_ui
37 from kallithea.lib.utils2 import HookEnvironmentError, ascii_str, get_hook_environment, safe_bytes, safe_str
37 from kallithea.lib.utils2 import HookEnvironmentError, ascii_str, get_hook_environment, safe_bytes
38 from kallithea.lib.vcs.backends.base import EmptyChangeset
38 from kallithea.lib.vcs.backends.base import EmptyChangeset
39 from kallithea.model.db import Repository, User
39 from kallithea.model.db import Repository, User
40
40
@@ -44,7 +44,7 b' def _get_scm_size(alias, root_path):'
44 alias += '.'
44 alias += '.'
45
45
46 size_scm, size_root = 0, 0
46 size_scm, size_root = 0, 0
47 for path, dirs, files in os.walk(safe_str(root_path)):
47 for path, dirs, files in os.walk(root_path):
48 if path.find(alias) != -1:
48 if path.find(alias) != -1:
49 for f in files:
49 for f in files:
50 try:
50 try:
@@ -318,8 +318,7 b' def _hook_environment(repo_path):'
318
318
319 repo = Repository.get_by_full_path(repo_path)
319 repo = Repository.get_by_full_path(repo_path)
320 if not repo:
320 if not repo:
321 raise OSError('Repository %s not found in database'
321 raise OSError('Repository %s not found in database' % repo_path)
322 % (safe_str(repo_path)))
323
322
324 baseui = make_ui()
323 baseui = make_ui()
325 return baseui, repo
324 return baseui, repo
@@ -397,5 +396,5 b' def handle_git_post_receive(repo_path, g'
397 def rejectpush(ui, **kwargs):
396 def rejectpush(ui, **kwargs):
398 """Mercurial hook to be installed as pretxnopen and prepushkey for read-only repos"""
397 """Mercurial hook to be installed as pretxnopen and prepushkey for read-only repos"""
399 ex = get_hook_environment()
398 ex = get_hook_environment()
400 ui.warn(safe_bytes("Push access to %r denied\n" % safe_str(ex.repository)))
399 ui.warn(safe_bytes("Push access to %r denied\n" % ex.repository))
401 return 1
400 return 1
@@ -39,7 +39,7 b' from whoosh.qparser import QueryParser'
39
39
40 from kallithea.config.conf import INDEX_EXTENSIONS, INDEX_FILENAMES
40 from kallithea.config.conf import INDEX_EXTENSIONS, INDEX_FILENAMES
41 from kallithea.lib.indexers import CHGSET_IDX_NAME, CHGSETS_SCHEMA, IDX_NAME, SCHEMA
41 from kallithea.lib.indexers import CHGSET_IDX_NAME, CHGSETS_SCHEMA, IDX_NAME, SCHEMA
42 from kallithea.lib.utils2 import safe_str, safe_unicode
42 from kallithea.lib.utils2 import safe_unicode
43 from kallithea.lib.vcs.exceptions import ChangesetError, NodeDoesNotExistError, RepositoryError
43 from kallithea.lib.vcs.exceptions import ChangesetError, NodeDoesNotExistError, RepositoryError
44 from kallithea.model.db import Repository
44 from kallithea.model.db import Repository
45 from kallithea.model.scm import ScmModel
45 from kallithea.model.scm import ScmModel
@@ -132,7 +132,7 b' class WhooshIndexingDaemon(object):'
132 cs = self._get_index_changeset(repo)
132 cs = self._get_index_changeset(repo)
133 for _topnode, _dirs, files in cs.walk('/'):
133 for _topnode, _dirs, files in cs.walk('/'):
134 for f in files:
134 for f in files:
135 index_paths_.add(os.path.join(safe_str(repo.path), safe_str(f.path)))
135 index_paths_.add(os.path.join(repo.path, f.path))
136
136
137 except RepositoryError:
137 except RepositoryError:
138 log.debug(traceback.format_exc())
138 log.debug(traceback.format_exc())
@@ -141,19 +141,16 b' class WhooshIndexingDaemon(object):'
141
141
142 def get_node(self, repo, path, index_rev=None):
142 def get_node(self, repo, path, index_rev=None):
143 """
143 """
144 gets a filenode based on given full path. It operates on string for
144 gets a filenode based on given full path.
145 hg git compatibility.
146
145
147 :param repo: scm repo instance
146 :param repo: scm repo instance
148 :param path: full path including root location
147 :param path: full path including root location
149 :return: FileNode
148 :return: FileNode
150 """
149 """
151 # FIXME: paths should be normalized ... or even better: don't include repo.path
150 # FIXME: paths should be normalized ... or even better: don't include repo.path
152 path = safe_str(path)
151 assert path.startswith(repo.path)
153 repo_path = safe_str(repo.path)
152 assert path[len(repo.path)] in (os.path.sep, os.path.altsep)
154 assert path.startswith(repo_path)
153 node_path = path[len(repo.path) + 1:]
155 assert path[len(repo_path)] in (os.path.sep, os.path.altsep)
156 node_path = path[len(repo_path) + 1:]
157 cs = self._get_index_changeset(repo, index_rev=index_rev)
154 cs = self._get_index_changeset(repo, index_rev=index_rev)
158 node = cs.get_node(node_path)
155 node = cs.get_node(node_path)
159 return node
156 return node
@@ -36,7 +36,7 b' import mercurial.hgweb'
36
36
37 from kallithea.lib.base import BaseVCSController, get_path_info
37 from kallithea.lib.base import BaseVCSController, get_path_info
38 from kallithea.lib.utils import make_ui
38 from kallithea.lib.utils import make_ui
39 from kallithea.lib.utils2 import safe_bytes, safe_str
39 from kallithea.lib.utils2 import safe_bytes
40
40
41
41
42 log = logging.getLogger(__name__)
42 log = logging.getLogger(__name__)
@@ -137,13 +137,13 b' class SimpleHg(BaseVCSController):'
137 """
137 """
138 Make an hgweb wsgi application.
138 Make an hgweb wsgi application.
139 """
139 """
140 str_repo_name = safe_str(parsed_request.repo_name)
140 repo_name = parsed_request.repo_name
141 repo_path = os.path.join(safe_str(self.basepath), str_repo_name)
141 repo_path = os.path.join(self.basepath, repo_name)
142 baseui = make_ui(repo_path=repo_path)
142 baseui = make_ui(repo_path=repo_path)
143 hgweb_app = mercurial.hgweb.hgweb(safe_bytes(repo_path), name=str_repo_name, baseui=baseui)
143 hgweb_app = mercurial.hgweb.hgweb(safe_bytes(repo_path), name=safe_bytes(repo_name), baseui=baseui)
144
144
145 def wrapper_app(environ, start_response):
145 def wrapper_app(environ, start_response):
146 environ['REPO_NAME'] = str_repo_name # used by mercurial.hgweb.hgweb
146 environ['REPO_NAME'] = repo_name # used by mercurial.hgweb.hgweb
147 return hgweb_app(environ, start_response)
147 return hgweb_app(environ, start_response)
148
148
149 return wrapper_app
149 return wrapper_app
@@ -40,7 +40,7 b' from tg.i18n import ugettext as _'
40
40
41 import kallithea.config.conf
41 import kallithea.config.conf
42 from kallithea.lib.exceptions import HgsubversionImportError
42 from kallithea.lib.exceptions import HgsubversionImportError
43 from kallithea.lib.utils2 import ascii_bytes, aslist, get_current_authuser, safe_bytes, safe_str
43 from kallithea.lib.utils2 import ascii_bytes, aslist, get_current_authuser, safe_bytes
44 from kallithea.lib.vcs.backends.git.repository import GitRepository
44 from kallithea.lib.vcs.backends.git.repository import GitRepository
45 from kallithea.lib.vcs.backends.hg.repository import MercurialRepository
45 from kallithea.lib.vcs.backends.hg.repository import MercurialRepository
46 from kallithea.lib.vcs.conf import settings
46 from kallithea.lib.vcs.conf import settings
@@ -174,7 +174,7 b' def get_filesystem_repos(path):'
174 """
174 """
175
175
176 # remove ending slash for better results
176 # remove ending slash for better results
177 path = safe_str(path.rstrip(os.sep))
177 path = path.rstrip(os.sep)
178 log.debug('now scanning in %s', path)
178 log.debug('now scanning in %s', path)
179
179
180 def isdir(*n):
180 def isdir(*n):
@@ -269,7 +269,7 b' def is_valid_repo(repo_name, base_path, '
269 :return True: if given path is a valid repository
269 :return True: if given path is a valid repository
270 """
270 """
271 # TODO: paranoid security checks?
271 # TODO: paranoid security checks?
272 full_path = os.path.join(safe_str(base_path), safe_str(repo_name))
272 full_path = os.path.join(base_path, repo_name)
273
273
274 try:
274 try:
275 scm_ = get_scm(full_path)
275 scm_ = get_scm(full_path)
@@ -287,7 +287,7 b' def is_valid_repo_group(repo_group_name,'
287 :param repo_name:
287 :param repo_name:
288 :param base_path:
288 :param base_path:
289 """
289 """
290 full_path = os.path.join(safe_str(base_path), safe_str(repo_group_name))
290 full_path = os.path.join(base_path, repo_group_name)
291
291
292 # check if it's not a repo
292 # check if it's not a repo
293 if is_valid_repo(repo_group_name, base_path):
293 if is_valid_repo(repo_group_name, base_path):
@@ -329,7 +329,7 b' def get_clone_url(clone_uri_tmpl, prefix'
329 system_user = 'kallithea' # hardcoded default value ...
329 system_user = 'kallithea' # hardcoded default value ...
330 args = {
330 args = {
331 'scheme': parsed_url.scheme,
331 'scheme': parsed_url.scheme,
332 'user': urllib.parse.quote(safe_str(username or '')),
332 'user': urllib.parse.quote(username or ''),
333 'netloc': parsed_url.netloc + prefix, # like "hostname:port/prefix" (with optional ":port" and "/prefix")
333 'netloc': parsed_url.netloc + prefix, # like "hostname:port/prefix" (with optional ":port" and "/prefix")
334 'prefix': prefix, # undocumented, empty or starting with /
334 'prefix': prefix, # undocumented, empty or starting with /
335 'repo': repo_name,
335 'repo': repo_name,
@@ -561,7 +561,7 b' class Optional(object):'
561
561
562
562
563 def urlreadable(s, _cleanstringsub=re.compile('[^-a-zA-Z0-9./]+').sub):
563 def urlreadable(s, _cleanstringsub=re.compile('[^-a-zA-Z0-9./]+').sub):
564 return _cleanstringsub('_', safe_str(s)).rstrip('_')
564 return _cleanstringsub('_', s).rstrip('_')
565
565
566
566
567 def recursive_replace(str_, replace=' '):
567 def recursive_replace(str_, replace=' '):
@@ -11,7 +11,7 b' from kallithea.lib.vcs.conf import setti'
11 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, ImproperArchiveTypeError, NodeDoesNotExistError, RepositoryError, VCSError
11 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, ImproperArchiveTypeError, NodeDoesNotExistError, RepositoryError, VCSError
12 from kallithea.lib.vcs.nodes import (
12 from kallithea.lib.vcs.nodes import (
13 AddedFileNodesGenerator, ChangedFileNodesGenerator, DirNode, FileNode, NodeKind, RemovedFileNodesGenerator, RootNode, SubModuleNode)
13 AddedFileNodesGenerator, ChangedFileNodesGenerator, DirNode, FileNode, NodeKind, RemovedFileNodesGenerator, RootNode, SubModuleNode)
14 from kallithea.lib.vcs.utils import ascii_bytes, ascii_str, date_fromtimestamp, safe_int, safe_str, safe_unicode
14 from kallithea.lib.vcs.utils import ascii_bytes, ascii_str, date_fromtimestamp, safe_int, safe_unicode
15 from kallithea.lib.vcs.utils.lazy import LazyProperty
15 from kallithea.lib.vcs.utils.lazy import LazyProperty
16
16
17
17
@@ -23,7 +23,6 b' class GitChangeset(BaseChangeset):'
23 def __init__(self, repository, revision):
23 def __init__(self, repository, revision):
24 self._stat_modes = {}
24 self._stat_modes = {}
25 self.repository = repository
25 self.repository = repository
26 revision = safe_str(revision)
27 try:
26 try:
28 commit = self.repository._repo[ascii_bytes(revision)]
27 commit = self.repository._repo[ascii_bytes(revision)]
29 if isinstance(commit, objects.Tag):
28 if isinstance(commit, objects.Tag):
@@ -109,7 +108,6 b' class GitChangeset(BaseChangeset):'
109 return path
108 return path
110
109
111 def _get_id_for_path(self, path):
110 def _get_id_for_path(self, path):
112 path = safe_str(path)
113 # FIXME: Please, spare a couple of minutes and make those codes cleaner;
111 # FIXME: Please, spare a couple of minutes and make those codes cleaner;
114 if path not in self._paths:
112 if path not in self._paths:
115 path = path.strip('/')
113 path = path.strip('/')
@@ -159,7 +157,7 b' class GitChangeset(BaseChangeset):'
159 if path not in self._paths:
157 if path not in self._paths:
160 raise NodeDoesNotExistError("There is no file nor directory "
158 raise NodeDoesNotExistError("There is no file nor directory "
161 "at the given path '%s' at revision %s"
159 "at the given path '%s' at revision %s"
162 % (path, safe_str(self.short_id)))
160 % (path, self.short_id))
163 return self._paths[path]
161 return self._paths[path]
164
162
165 def _get_kind(self, path):
163 def _get_kind(self, path):
@@ -252,7 +250,6 b' class GitChangeset(BaseChangeset):'
252 Returns stat mode of the file at the given ``path``.
250 Returns stat mode of the file at the given ``path``.
253 """
251 """
254 # ensure path is traversed
252 # ensure path is traversed
255 path = safe_str(path)
256 self._get_id_for_path(path)
253 self._get_id_for_path(path)
257 return self._stat_modes[path]
254 return self._stat_modes[path]
258
255
@@ -288,15 +285,14 b' class GitChangeset(BaseChangeset):'
288 iterating commits.
285 iterating commits.
289 """
286 """
290 self._get_filectx(path)
287 self._get_filectx(path)
291 f_path = safe_str(path)
292
288
293 if limit is not None:
289 if limit is not None:
294 cmd = ['log', '-n', str(safe_int(limit, 0)),
290 cmd = ['log', '-n', str(safe_int(limit, 0)),
295 '--pretty=format:%H', '-s', self.raw_id, '--', f_path]
291 '--pretty=format:%H', '-s', self.raw_id, '--', path]
296
292
297 else:
293 else:
298 cmd = ['log',
294 cmd = ['log',
299 '--pretty=format:%H', '-s', self.raw_id, '--', f_path]
295 '--pretty=format:%H', '-s', self.raw_id, '--', path]
300 so = self.repository.run_git_command(cmd)
296 so = self.repository.run_git_command(cmd)
301 ids = re.findall(r'[0-9a-fA-F]{40}', so)
297 ids = re.findall(r'[0-9a-fA-F]{40}', so)
302 return [self.repository.get_changeset(sha) for sha in ids]
298 return [self.repository.get_changeset(sha) for sha in ids]
@@ -30,7 +30,7 b' from kallithea.lib.vcs.backends.base imp'
30 from kallithea.lib.vcs.conf import settings
30 from kallithea.lib.vcs.conf import settings
31 from kallithea.lib.vcs.exceptions import (
31 from kallithea.lib.vcs.exceptions import (
32 BranchDoesNotExistError, ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError, TagAlreadyExistError, TagDoesNotExistError)
32 BranchDoesNotExistError, ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError, TagAlreadyExistError, TagDoesNotExistError)
33 from kallithea.lib.vcs.utils import ascii_str, date_fromtimestamp, makedate, safe_bytes, safe_str, safe_unicode
33 from kallithea.lib.vcs.utils import ascii_str, date_fromtimestamp, makedate, safe_bytes, safe_unicode
34 from kallithea.lib.vcs.utils.lazy import LazyProperty
34 from kallithea.lib.vcs.utils.lazy import LazyProperty
35 from kallithea.lib.vcs.utils.paths import abspath, get_user_home
35 from kallithea.lib.vcs.utils.paths import abspath, get_user_home
36
36
@@ -317,7 +317,6 b' class GitRepository(BaseRepository):'
317 Returns normalized url. If schema is not given, would fall to
317 Returns normalized url. If schema is not given, would fall to
318 filesystem (``file:///``) schema.
318 filesystem (``file:///``) schema.
319 """
319 """
320 url = safe_str(url)
321 if url != 'default' and '://' not in url:
320 if url != 'default' and '://' not in url:
322 url = ':///'.join(('file', url))
321 url = ':///'.join(('file', url))
323 return url
322 return url
@@ -18,7 +18,6 b' import os'
18 from kallithea.lib.hooks import log_pull_action
18 from kallithea.lib.hooks import log_pull_action
19 from kallithea.lib.utils import make_ui
19 from kallithea.lib.utils import make_ui
20 from kallithea.lib.vcs.backends.ssh import BaseSshHandler
20 from kallithea.lib.vcs.backends.ssh import BaseSshHandler
21 from kallithea.lib.vcs.utils import safe_str
22
21
23
22
24 log = logging.getLogger(__name__)
23 log = logging.getLogger(__name__)
@@ -70,7 +69,7 b' class GitSshHandler(BaseSshHandler):'
70 log_pull_action(ui=make_ui(), repo=self.db_repo.scm_instance._repo)
69 log_pull_action(ui=make_ui(), repo=self.db_repo.scm_instance._repo)
71 else: # probably verb 'git-receive-pack', action 'push'
70 else: # probably verb 'git-receive-pack', action 'push'
72 if not self.allow_push:
71 if not self.allow_push:
73 self.exit('Push access to %r denied' % safe_str(self.repo_name))
72 self.exit('Push access to %r denied' % self.repo_name)
74 # Note: push logging is handled by Git post-receive hook
73 # Note: push logging is handled by Git post-receive hook
75
74
76 # git shell is not a real shell but use shell inspired quoting *inside* the argument.
75 # git shell is not a real shell but use shell inspired quoting *inside* the argument.
@@ -10,7 +10,7 b' from kallithea.lib.vcs.conf import setti'
10 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, ImproperArchiveTypeError, NodeDoesNotExistError, VCSError
10 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, ImproperArchiveTypeError, NodeDoesNotExistError, VCSError
11 from kallithea.lib.vcs.nodes import (
11 from kallithea.lib.vcs.nodes import (
12 AddedFileNodesGenerator, ChangedFileNodesGenerator, DirNode, FileNode, NodeKind, RemovedFileNodesGenerator, RootNode, SubModuleNode)
12 AddedFileNodesGenerator, ChangedFileNodesGenerator, DirNode, FileNode, NodeKind, RemovedFileNodesGenerator, RootNode, SubModuleNode)
13 from kallithea.lib.vcs.utils import ascii_bytes, ascii_str, date_fromtimestamp, safe_bytes, safe_str, safe_unicode
13 from kallithea.lib.vcs.utils import ascii_bytes, ascii_str, date_fromtimestamp, safe_bytes, safe_unicode
14 from kallithea.lib.vcs.utils.lazy import LazyProperty
14 from kallithea.lib.vcs.utils.lazy import LazyProperty
15 from kallithea.lib.vcs.utils.paths import get_dirs_for_path
15 from kallithea.lib.vcs.utils.paths import get_dirs_for_path
16
16
@@ -202,7 +202,7 b' class MercurialChangeset(BaseChangeset):'
202 if path.endswith('/'):
202 if path.endswith('/'):
203 path = path.rstrip('/')
203 path = path.rstrip('/')
204
204
205 return safe_str(path)
205 return path
206
206
207 def _get_kind(self, path):
207 def _get_kind(self, path):
208 path = self._fix_path(path)
208 path = self._fix_path(path)
@@ -39,7 +39,7 b' import mercurial.util'
39 from kallithea.lib.vcs.backends.base import BaseRepository, CollectionGenerator
39 from kallithea.lib.vcs.backends.base import BaseRepository, CollectionGenerator
40 from kallithea.lib.vcs.exceptions import (
40 from kallithea.lib.vcs.exceptions import (
41 BranchDoesNotExistError, ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError, TagAlreadyExistError, TagDoesNotExistError, VCSError)
41 BranchDoesNotExistError, ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError, TagAlreadyExistError, TagDoesNotExistError, VCSError)
42 from kallithea.lib.vcs.utils import ascii_str, author_email, author_name, date_fromtimestamp, makedate, safe_bytes, safe_str, safe_unicode
42 from kallithea.lib.vcs.utils import ascii_str, author_email, author_name, date_fromtimestamp, makedate, safe_bytes, safe_unicode
43 from kallithea.lib.vcs.utils.lazy import LazyProperty
43 from kallithea.lib.vcs.utils.lazy import LazyProperty
44 from kallithea.lib.vcs.utils.paths import abspath
44 from kallithea.lib.vcs.utils.paths import abspath
45
45
@@ -446,7 +446,6 b' class MercurialRepository(BaseRepository'
446 """
446 """
447 Returns revision number for the given reference.
447 Returns revision number for the given reference.
448 """
448 """
449 ref_name = safe_str(ref_name)
450 if ref_type == 'rev' and not ref_name.strip('0'):
449 if ref_type == 'rev' and not ref_name.strip('0'):
451 return self.EMPTY_CHANGESET
450 return self.EMPTY_CHANGESET
452 # lookup up the exact node id
451 # lookup up the exact node id
@@ -485,11 +484,9 b' class MercurialRepository(BaseRepository'
485
484
486 def _get_url(self, url):
485 def _get_url(self, url):
487 """
486 """
488 Returns normalized url. If schema is not given, would fall
487 Returns normalized url. If schema is not given, fall back to
489 to filesystem
488 filesystem (``file:///``) schema.
490 (``file:///``) schema.
491 """
489 """
492 url = safe_str(url)
493 if url != 'default' and '://' not in url:
490 if url != 'default' and '://' not in url:
494 url = "file:" + urllib.request.pathname2url(url)
491 url = "file:" + urllib.request.pathname2url(url)
495 return url
492 return url
@@ -25,7 +25,6 b' import sys'
25
25
26 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
26 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
27 from kallithea.lib.utils2 import set_hook_environment
27 from kallithea.lib.utils2 import set_hook_environment
28 from kallithea.lib.vcs.utils import safe_str
29 from kallithea.model.db import Repository, User, UserSshKeys
28 from kallithea.model.db import Repository, User, UserSshKeys
30 from kallithea.model.meta import Session
29 from kallithea.model.meta import Session
31
30
@@ -83,7 +82,7 b' class BaseSshHandler(object):'
83 elif HasPermissionAnyMiddleware('repository.read')(self.authuser, self.repo_name):
82 elif HasPermissionAnyMiddleware('repository.read')(self.authuser, self.repo_name):
84 self.allow_push = False
83 self.allow_push = False
85 else:
84 else:
86 self.exit('Access to %r denied' % safe_str(self.repo_name))
85 self.exit('Access to %r denied' % self.repo_name)
87
86
88 self.db_repo = Repository.get_by_repo_name(self.repo_name)
87 self.db_repo = Repository.get_by_repo_name(self.repo_name)
89 if self.db_repo is None:
88 if self.db_repo is None:
@@ -16,7 +16,7 b' import stat'
16
16
17 from kallithea.lib.vcs.backends.base import EmptyChangeset
17 from kallithea.lib.vcs.backends.base import EmptyChangeset
18 from kallithea.lib.vcs.exceptions import NodeError, RemovedFileNodeError
18 from kallithea.lib.vcs.exceptions import NodeError, RemovedFileNodeError
19 from kallithea.lib.vcs.utils import safe_bytes, safe_str, safe_unicode
19 from kallithea.lib.vcs.utils import safe_bytes, safe_unicode
20 from kallithea.lib.vcs.utils.lazy import LazyProperty
20 from kallithea.lib.vcs.utils.lazy import LazyProperty
21
21
22
22
@@ -102,7 +102,7 b' class Node(object):'
102 if path.startswith('/'):
102 if path.startswith('/'):
103 raise NodeError("Cannot initialize Node objects with slash at "
103 raise NodeError("Cannot initialize Node objects with slash at "
104 "the beginning as only relative paths are supported")
104 "the beginning as only relative paths are supported")
105 self.path = safe_str(path.rstrip('/')) # we store paths as str
105 self.path = path.rstrip('/')
106 if path == '' and kind != NodeKind.DIR:
106 if path == '' and kind != NodeKind.DIR:
107 raise NodeError("Only DirNode and its subclasses may be "
107 raise NodeError("Only DirNode and its subclasses may be "
108 "initialized with empty path")
108 "initialized with empty path")
@@ -592,7 +592,7 b' class SubModuleNode(Node):'
592 self.alias = alias
592 self.alias = alias
593 # we have to use emptyChangeset here since this can point to svn/git/hg
593 # we have to use emptyChangeset here since this can point to svn/git/hg
594 # submodules we cannot get from repository
594 # submodules we cannot get from repository
595 self.changeset = EmptyChangeset(str(changeset), alias=alias)
595 self.changeset = EmptyChangeset(changeset, alias=alias)
596 self.url = url
596 self.url = url
597
597
598 def __repr__(self):
598 def __repr__(self):
@@ -204,7 +204,7 b' def author_email(author):'
204 m = email_re.search(author)
204 m = email_re.search(author)
205 if m is None:
205 if m is None:
206 return ''
206 return ''
207 return safe_str(m.group(0))
207 return m.group(0)
208
208
209
209
210 def author_name(author):
210 def author_name(author):
@@ -49,7 +49,7 b' from kallithea.lib import ext_json'
49 from kallithea.lib.caching_query import FromCache
49 from kallithea.lib.caching_query import FromCache
50 from kallithea.lib.exceptions import DefaultUserException
50 from kallithea.lib.exceptions import DefaultUserException
51 from kallithea.lib.utils2 import (
51 from kallithea.lib.utils2 import (
52 Optional, ascii_bytes, aslist, get_changeset_safe, get_clone_url, remove_prefix, safe_bytes, safe_int, safe_str, safe_unicode, str2bool, urlreadable)
52 Optional, ascii_bytes, aslist, get_changeset_safe, get_clone_url, remove_prefix, safe_bytes, safe_int, safe_unicode, str2bool, urlreadable)
53 from kallithea.lib.vcs import get_backend
53 from kallithea.lib.vcs import get_backend
54 from kallithea.lib.vcs.backends.base import EmptyChangeset
54 from kallithea.lib.vcs.backends.base import EmptyChangeset
55 from kallithea.lib.vcs.utils.helpers import get_scm
55 from kallithea.lib.vcs.utils.helpers import get_scm
@@ -1424,7 +1424,7 b' class Repository(Base, BaseDbModel):'
1424 return _c(rn)
1424 return _c(rn)
1425
1425
1426 def scm_instance_no_cache(self):
1426 def scm_instance_no_cache(self):
1427 repo_full_path = safe_str(self.repo_full_path)
1427 repo_full_path = self.repo_full_path
1428 alias = get_scm(repo_full_path)[0]
1428 alias = get_scm(repo_full_path)[0]
1429 log.debug('Creating instance of %s repository from %s',
1429 log.debug('Creating instance of %s repository from %s',
1430 alias, self.repo_full_path)
1430 alias, self.repo_full_path)
@@ -2091,11 +2091,11 b' class CacheInvalidation(Base, BaseDbMode'
2091 """
2091 """
2092 inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
2092 inv_objs = Session().query(cls).filter(cls.cache_args == repo_name).all()
2093 log.debug('for repo %s got %s invalidation objects',
2093 log.debug('for repo %s got %s invalidation objects',
2094 safe_str(repo_name), inv_objs)
2094 repo_name, inv_objs)
2095
2095
2096 for inv_obj in inv_objs:
2096 for inv_obj in inv_objs:
2097 log.debug('marking %s key for invalidation based on repo_name=%s',
2097 log.debug('marking %s key for invalidation based on repo_name=%s',
2098 inv_obj, safe_str(repo_name))
2098 inv_obj, repo_name)
2099 Session().delete(inv_obj)
2099 Session().delete(inv_obj)
2100 Session().commit()
2100 Session().commit()
2101
2101
@@ -2517,7 +2517,7 b' class Gist(Base, BaseDbModel):'
2517 def scm_instance(self):
2517 def scm_instance(self):
2518 from kallithea.lib.vcs import get_repo
2518 from kallithea.lib.vcs import get_repo
2519 base_path = self.base_path()
2519 base_path = self.base_path()
2520 return get_repo(os.path.join(safe_str(base_path), safe_str(self.gist_access_id)))
2520 return get_repo(os.path.join(base_path, self.gist_access_id))
2521
2521
2522
2522
2523 class UserSshKeys(Base, BaseDbModel):
2523 class UserSshKeys(Base, BaseDbModel):
@@ -39,7 +39,7 b' from kallithea.lib.caching_query import '
39 from kallithea.lib.exceptions import AttachedForksError
39 from kallithea.lib.exceptions import AttachedForksError
40 from kallithea.lib.hooks import log_delete_repository
40 from kallithea.lib.hooks import log_delete_repository
41 from kallithea.lib.utils import is_valid_repo_uri, make_ui
41 from kallithea.lib.utils import is_valid_repo_uri, make_ui
42 from kallithea.lib.utils2 import LazyProperty, get_current_authuser, obfuscate_url_pw, remove_prefix, safe_str
42 from kallithea.lib.utils2 import LazyProperty, get_current_authuser, obfuscate_url_pw, remove_prefix
43 from kallithea.lib.vcs.backends import get_backend
43 from kallithea.lib.vcs.backends import get_backend
44 from kallithea.model.db import (
44 from kallithea.model.db import (
45 Permission, RepoGroup, Repository, RepositoryField, Session, Statistics, Ui, User, UserGroup, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserRepoGroupToPerm, UserRepoToPerm)
45 Permission, RepoGroup, Repository, RepositoryField, Session, Statistics, Ui, User, UserGroup, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserRepoGroupToPerm, UserRepoToPerm)
@@ -641,8 +641,7 b' class RepoModel(object):'
641 _paths = [repo_store_location]
641 _paths = [repo_store_location]
642 else:
642 else:
643 _paths = [self.repos_path, new_parent_path, repo_name]
643 _paths = [self.repos_path, new_parent_path, repo_name]
644 # we need to make it str for mercurial
644 repo_path = os.path.join(*_paths)
645 repo_path = os.path.join(*(safe_str(x) for x in _paths))
646
645
647 # check if this path is not a repository
646 # check if this path is not a repository
648 if is_valid_repo(repo_path, self.repos_path):
647 if is_valid_repo(repo_path, self.repos_path):
@@ -686,8 +685,8 b' class RepoModel(object):'
686 """
685 """
687 log.info('renaming repo from %s to %s', old, new)
686 log.info('renaming repo from %s to %s', old, new)
688
687
689 old_path = safe_str(os.path.join(self.repos_path, old))
688 old_path = os.path.join(self.repos_path, old)
690 new_path = safe_str(os.path.join(self.repos_path, new))
689 new_path = os.path.join(self.repos_path, new)
691 if os.path.isdir(new_path):
690 if os.path.isdir(new_path):
692 raise Exception(
691 raise Exception(
693 'Was trying to rename to already existing dir %s' % new_path
692 'Was trying to rename to already existing dir %s' % new_path
@@ -702,7 +701,7 b' class RepoModel(object):'
702
701
703 :param repo: repo object
702 :param repo: repo object
704 """
703 """
705 rm_path = safe_str(os.path.join(self.repos_path, repo.repo_name))
704 rm_path = os.path.join(self.repos_path, repo.repo_name)
706 log.info("Removing %s", rm_path)
705 log.info("Removing %s", rm_path)
707
706
708 _now = datetime.now()
707 _now = datetime.now()
@@ -713,6 +712,6 b' class RepoModel(object):'
713 args = repo.group.full_path_splitted + [_d]
712 args = repo.group.full_path_splitted + [_d]
714 _d = os.path.join(*args)
713 _d = os.path.join(*args)
715 if os.path.exists(rm_path):
714 if os.path.exists(rm_path):
716 shutil.move(rm_path, safe_str(os.path.join(self.repos_path, _d)))
715 shutil.move(rm_path, os.path.join(self.repos_path, _d))
717 else:
716 else:
718 log.error("Can't find repo to delete in %r", rm_path)
717 log.error("Can't find repo to delete in %r", rm_path)
@@ -41,7 +41,7 b' from kallithea.lib.auth import HasPermis'
41 from kallithea.lib.exceptions import IMCCommitError, NonRelativePathError
41 from kallithea.lib.exceptions import IMCCommitError, NonRelativePathError
42 from kallithea.lib.hooks import process_pushed_raw_ids
42 from kallithea.lib.hooks import process_pushed_raw_ids
43 from kallithea.lib.utils import action_logger, get_filesystem_repos, make_ui
43 from kallithea.lib.utils import action_logger, get_filesystem_repos, make_ui
44 from kallithea.lib.utils2 import safe_bytes, safe_str, set_hook_environment
44 from kallithea.lib.utils2 import safe_bytes, set_hook_environment
45 from kallithea.lib.vcs import get_backend
45 from kallithea.lib.vcs import get_backend
46 from kallithea.lib.vcs.backends.base import EmptyChangeset
46 from kallithea.lib.vcs.backends.base import EmptyChangeset
47 from kallithea.lib.vcs.exceptions import RepositoryError
47 from kallithea.lib.vcs.exceptions import RepositoryError
@@ -190,7 +190,7 b' class ScmModel(object):'
190 klass = get_backend(path[0])
190 klass = get_backend(path[0])
191
191
192 if path[0] == 'hg' and path[0] in BACKENDS:
192 if path[0] == 'hg' and path[0] in BACKENDS:
193 repos[name] = klass(safe_str(path[1]), baseui=baseui)
193 repos[name] = klass(path[1], baseui=baseui)
194
194
195 if path[0] == 'git' and path[0] in BACKENDS:
195 if path[0] == 'git' and path[0] in BACKENDS:
196 repos[name] = klass(path[1])
196 repos[name] = klass(path[1])
@@ -396,13 +396,8 b' class ScmModel(object):'
396 """
396 """
397 user = User.guess_instance(user)
397 user = User.guess_instance(user)
398 IMC = self._get_IMC_module(repo.alias)
398 IMC = self._get_IMC_module(repo.alias)
399
400 # decoding here will force that we have proper encoded values
401 # in any other case this will throw exceptions and deny commit
402 content = safe_str(content)
403 path = safe_str(f_path)
404 imc = IMC(repo)
399 imc = IMC(repo)
405 imc.change(FileNode(path, content, mode=cs.get_file_mode(f_path)))
400 imc.change(FileNode(f_path, content, mode=cs.get_file_mode(f_path)))
406 try:
401 try:
407 tip = imc.commit(message=message, author=author,
402 tip = imc.commit(message=message, author=author,
408 parents=[cs], branch=cs.branch)
403 parents=[cs], branch=cs.branch)
@@ -478,12 +473,7 b' class ScmModel(object):'
478 for f_path in nodes:
473 for f_path in nodes:
479 content = nodes[f_path]['content']
474 content = nodes[f_path]['content']
480 f_path = self._sanitize_path(f_path)
475 f_path = self._sanitize_path(f_path)
481 f_path = safe_str(f_path)
476 if not isinstance(content, str) and not isinstance(content, bytes):
482 # decoding here will force that we have proper encoded values
483 # in any other case this will throw exceptions and deny commit
484 if isinstance(content, (str,)):
485 content = safe_str(content)
486 else:
487 content = content.read()
477 content = content.read()
488 processed_nodes.append((f_path, content))
478 processed_nodes.append((f_path, content))
489
479
@@ -22,7 +22,7 b' import time'
22 import pytest
22 import pytest
23 from webtest import TestApp
23 from webtest import TestApp
24
24
25 from kallithea.lib.utils2 import ascii_str, safe_str
25 from kallithea.lib.utils2 import ascii_str
26 from kallithea.model.db import User
26 from kallithea.model.db import User
27
27
28
28
@@ -180,16 +180,15 b' class TestController(object):'
180
180
181 def checkSessionFlash(self, response, msg=None, skip=0, _matcher=lambda msg, m: msg in m):
181 def checkSessionFlash(self, response, msg=None, skip=0, _matcher=lambda msg, m: msg in m):
182 if 'flash' not in response.session:
182 if 'flash' not in response.session:
183 pytest.fail(safe_str(u'msg `%s` not found - session has no flash:\n%s' % (msg, response)))
183 pytest.fail(u'msg `%s` not found - session has no flash:\n%s' % (msg, response))
184 try:
184 try:
185 level, m = response.session['flash'][-1 - skip]
185 level, m = response.session['flash'][-1 - skip]
186 if _matcher(msg, m):
186 if _matcher(msg, m):
187 return
187 return
188 except IndexError:
188 except IndexError:
189 pass
189 pass
190 pytest.fail(safe_str(u'msg `%s` not found in session flash (skipping %s): %s' %
190 pytest.fail(u'msg `%s` not found in session flash (skipping %s): %s' %
191 (msg, skip,
191 (msg, skip, ', '.join('`%s`' % m for level, m in response.session['flash'])))
192 ', '.join('`%s`' % m for level, m in response.session['flash']))))
193
192
194 def checkSessionFlashRegex(self, response, regex, skip=0):
193 def checkSessionFlashRegex(self, response, regex, skip=0):
195 self.checkSessionFlash(response, regex, skip=skip, _matcher=re.search)
194 self.checkSessionFlash(response, regex, skip=skip, _matcher=re.search)
@@ -7,7 +7,6 b' import mock'
7 import pytest
7 import pytest
8
8
9 from kallithea.lib import vcs
9 from kallithea.lib import vcs
10 from kallithea.lib.utils2 import safe_str
11 from kallithea.model.db import Permission, RepoGroup, Repository, Ui, User, UserRepoToPerm
10 from kallithea.model.db import Permission, RepoGroup, Repository, Ui, User, UserRepoToPerm
12 from kallithea.model.meta import Session
11 from kallithea.model.meta import Session
13 from kallithea.model.repo import RepoModel
12 from kallithea.model.repo import RepoModel
@@ -74,7 +73,7 b' class _BaseTestCase(base.TestController)'
74
73
75 # test if the repository was created on filesystem
74 # test if the repository was created on filesystem
76 try:
75 try:
77 vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)))
76 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
78 except vcs.exceptions.VCSError:
77 except vcs.exceptions.VCSError:
79 pytest.fail('no repo %s in filesystem' % repo_name)
78 pytest.fail('no repo %s in filesystem' % repo_name)
80
79
@@ -149,7 +148,7 b' class _BaseTestCase(base.TestController)'
149
148
150 # test if the repository was created on filesystem
149 # test if the repository was created on filesystem
151 try:
150 try:
152 vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full)))
151 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full))
153 except vcs.exceptions.VCSError:
152 except vcs.exceptions.VCSError:
154 RepoGroupModel().delete(group_name)
153 RepoGroupModel().delete(group_name)
155 Session().commit()
154 Session().commit()
@@ -241,7 +240,7 b' class _BaseTestCase(base.TestController)'
241
240
242 # test if the repository was created on filesystem
241 # test if the repository was created on filesystem
243 try:
242 try:
244 vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full)))
243 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full))
245 except vcs.exceptions.VCSError:
244 except vcs.exceptions.VCSError:
246 RepoGroupModel().delete(group_name)
245 RepoGroupModel().delete(group_name)
247 Session().commit()
246 Session().commit()
@@ -298,7 +297,7 b' class _BaseTestCase(base.TestController)'
298
297
299 # test if the repository was created on filesystem
298 # test if the repository was created on filesystem
300 try:
299 try:
301 vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full)))
300 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_full))
302 except vcs.exceptions.VCSError:
301 except vcs.exceptions.VCSError:
303 RepoGroupModel().delete(group_name)
302 RepoGroupModel().delete(group_name)
304 Session().commit()
303 Session().commit()
@@ -373,7 +372,7 b' class _BaseTestCase(base.TestController)'
373
372
374 # test if the repository was created on filesystem
373 # test if the repository was created on filesystem
375 try:
374 try:
376 vcs.get_repo(safe_str(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name)))
375 vcs.get_repo(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name))
377 except vcs.exceptions.VCSError:
376 except vcs.exceptions.VCSError:
378 pytest.fail('no repo %s in filesystem' % repo_name)
377 pytest.fail('no repo %s in filesystem' % repo_name)
379
378
@@ -395,7 +394,7 b' class _BaseTestCase(base.TestController)'
395 def test_delete_non_ascii(self):
394 def test_delete_non_ascii(self):
396 self.log_user()
395 self.log_user()
397 non_ascii = "Δ…Δ™Ε‚"
396 non_ascii = "Δ…Δ™Ε‚"
398 repo_name = "%s%s" % (safe_str(self.NEW_REPO), non_ascii)
397 repo_name = "%s%s" % (self.NEW_REPO, non_ascii)
399 description = 'description for newly created repo' + non_ascii
398 description = 'description for newly created repo' + non_ascii
400 response = self.app.post(base.url('repos'),
399 response = self.app.post(base.url('repos'),
401 fixture._get_repo_create_params(repo_private=False,
400 fixture._get_repo_create_params(repo_private=False,
@@ -2,7 +2,6 b''
2
2
3 import urllib.parse
3 import urllib.parse
4
4
5 from kallithea.lib.utils2 import safe_str
6 from kallithea.model.db import Repository, User
5 from kallithea.model.db import Repository, User
7 from kallithea.model.meta import Session
6 from kallithea.model.meta import Session
8 from kallithea.model.repo import RepoModel
7 from kallithea.model.repo import RepoModel
@@ -144,7 +143,7 b' class _BaseTestCase(base.TestController)'
144 # create a fork
143 # create a fork
145 repo_name = self.REPO
144 repo_name = self.REPO
146 org_repo = Repository.get_by_repo_name(repo_name)
145 org_repo = Repository.get_by_repo_name(repo_name)
147 fork_name = safe_str(self.REPO_FORK + u'-rΓΈdgrΓΈd')
146 fork_name = self.REPO_FORK + u'-rΓΈdgrΓΈd'
148 creation_args = {
147 creation_args = {
149 'repo_name': fork_name,
148 'repo_name': fork_name,
150 'repo_group': u'-1',
149 'repo_group': u'-1',
@@ -165,7 +164,7 b' class _BaseTestCase(base.TestController)'
165 assert fork_repo
164 assert fork_repo
166
165
167 # fork the fork
166 # fork the fork
168 fork_name_2 = safe_str(self.REPO_FORK + u'-blΓ₯bΓ¦rgrΓΈd')
167 fork_name_2 = self.REPO_FORK + u'-blΓ₯bΓ¦rgrΓΈd'
169 creation_args = {
168 creation_args = {
170 'repo_name': fork_name_2,
169 'repo_name': fork_name_2,
171 'repo_group': u'-1',
170 'repo_group': u'-1',
@@ -6,7 +6,6 b' import pytest'
6 from kallithea.lib.vcs.backends.hg import MercurialChangeset, MercurialRepository
6 from kallithea.lib.vcs.backends.hg import MercurialChangeset, MercurialRepository
7 from kallithea.lib.vcs.exceptions import NodeDoesNotExistError, RepositoryError, VCSError
7 from kallithea.lib.vcs.exceptions import NodeDoesNotExistError, RepositoryError, VCSError
8 from kallithea.lib.vcs.nodes import NodeKind, NodeState
8 from kallithea.lib.vcs.nodes import NodeKind, NodeState
9 from kallithea.lib.vcs.utils import safe_str
10 from kallithea.tests.vcs.conf import TEST_HG_REPO, TEST_HG_REPO_CLONE, TEST_HG_REPO_PULL, TESTS_TMP_PATH
9 from kallithea.tests.vcs.conf import TEST_HG_REPO, TEST_HG_REPO_CLONE, TEST_HG_REPO_PULL, TESTS_TMP_PATH
11
10
12
11
@@ -19,7 +18,7 b' class TestMercurialRepository(object):'
19 % TEST_HG_REPO_CLONE)
18 % TEST_HG_REPO_CLONE)
20
19
21 def setup_method(self):
20 def setup_method(self):
22 self.repo = MercurialRepository(safe_str(TEST_HG_REPO))
21 self.repo = MercurialRepository(TEST_HG_REPO)
23
22
24 def test_wrong_repo_path(self):
23 def test_wrong_repo_path(self):
25 wrong_repo_path = os.path.join(TESTS_TMP_PATH, 'errorrepo')
24 wrong_repo_path = os.path.join(TESTS_TMP_PATH, 'errorrepo')
@@ -32,7 +31,7 b' class TestMercurialRepository(object):'
32
31
33 def test_repo_clone(self):
32 def test_repo_clone(self):
34 self.__check_for_existing_repo()
33 self.__check_for_existing_repo()
35 repo = MercurialRepository(safe_str(TEST_HG_REPO))
34 repo = MercurialRepository(TEST_HG_REPO)
36 repo_clone = MercurialRepository(TEST_HG_REPO_CLONE,
35 repo_clone = MercurialRepository(TEST_HG_REPO_CLONE,
37 src_url=TEST_HG_REPO, update_after_clone=True)
36 src_url=TEST_HG_REPO, update_after_clone=True)
38 assert len(repo.revisions) == len(repo_clone.revisions)
37 assert len(repo.revisions) == len(repo_clone.revisions)
@@ -42,7 +41,7 b' class TestMercurialRepository(object):'
42 assert raw_id == repo_clone.get_changeset(raw_id).raw_id
41 assert raw_id == repo_clone.get_changeset(raw_id).raw_id
43
42
44 def test_repo_clone_with_update(self):
43 def test_repo_clone_with_update(self):
45 repo = MercurialRepository(safe_str(TEST_HG_REPO))
44 repo = MercurialRepository(TEST_HG_REPO)
46 repo_clone = MercurialRepository(TEST_HG_REPO_CLONE + '_w_update',
45 repo_clone = MercurialRepository(TEST_HG_REPO_CLONE + '_w_update',
47 src_url=TEST_HG_REPO, update_after_clone=True)
46 src_url=TEST_HG_REPO, update_after_clone=True)
48 assert len(repo.revisions) == len(repo_clone.revisions)
47 assert len(repo.revisions) == len(repo_clone.revisions)
@@ -55,7 +54,7 b' class TestMercurialRepository(object):'
55 )
54 )
56
55
57 def test_repo_clone_without_update(self):
56 def test_repo_clone_without_update(self):
58 repo = MercurialRepository(safe_str(TEST_HG_REPO))
57 repo = MercurialRepository(TEST_HG_REPO)
59 repo_clone = MercurialRepository(TEST_HG_REPO_CLONE + '_wo_update',
58 repo_clone = MercurialRepository(TEST_HG_REPO_CLONE + '_wo_update',
60 src_url=TEST_HG_REPO, update_after_clone=False)
59 src_url=TEST_HG_REPO, update_after_clone=False)
61 assert len(repo.revisions) == len(repo_clone.revisions)
60 assert len(repo.revisions) == len(repo_clone.revisions)
@@ -256,7 +255,7 b' TODO: To be written...'
256 class TestMercurialChangeset(object):
255 class TestMercurialChangeset(object):
257
256
258 def setup_method(self):
257 def setup_method(self):
259 self.repo = MercurialRepository(safe_str(TEST_HG_REPO))
258 self.repo = MercurialRepository(TEST_HG_REPO)
260
259
261 def _test_equality(self, changeset):
260 def _test_equality(self, changeset):
262 revision = changeset.revision
261 revision = changeset.revision
@@ -5,7 +5,6 b' import pytest'
5
5
6 from kallithea.lib.vcs import VCSError, get_backend, get_repo
6 from kallithea.lib.vcs import VCSError, get_backend, get_repo
7 from kallithea.lib.vcs.backends.hg import MercurialRepository
7 from kallithea.lib.vcs.backends.hg import MercurialRepository
8 from kallithea.lib.vcs.utils import safe_str
9 from kallithea.tests.vcs.conf import TEST_GIT_REPO, TEST_HG_REPO, TESTS_TMP_PATH
8 from kallithea.tests.vcs.conf import TEST_GIT_REPO, TEST_HG_REPO, TESTS_TMP_PATH
10
9
11
10
@@ -22,14 +21,14 b' class TestVCS(object):'
22 alias = 'hg'
21 alias = 'hg'
23 path = TEST_HG_REPO
22 path = TEST_HG_REPO
24 backend = get_backend(alias)
23 backend = get_backend(alias)
25 repo = backend(safe_str(path))
24 repo = backend(path)
26 assert 'hg' == repo.alias
25 assert 'hg' == repo.alias
27
26
28 def test_alias_detect_git(self):
27 def test_alias_detect_git(self):
29 alias = 'git'
28 alias = 'git'
30 path = TEST_GIT_REPO
29 path = TEST_GIT_REPO
31 backend = get_backend(alias)
30 backend = get_backend(alias)
32 repo = backend(safe_str(path))
31 repo = backend(path)
33 assert 'git' == repo.alias
32 assert 'git' == repo.alias
34
33
35 def test_wrong_alias(self):
34 def test_wrong_alias(self):
@@ -41,28 +40,28 b' class TestVCS(object):'
41 alias = 'hg'
40 alias = 'hg'
42 path = TEST_HG_REPO
41 path = TEST_HG_REPO
43 backend = get_backend(alias)
42 backend = get_backend(alias)
44 repo = backend(safe_str(path))
43 repo = backend(path)
45
44
46 assert repo.__class__ == get_repo(safe_str(path), alias).__class__
45 assert repo.__class__ == get_repo(path, alias).__class__
47 assert repo.path == get_repo(safe_str(path), alias).path
46 assert repo.path == get_repo(path, alias).path
48
47
49 def test_get_repo_autoalias_hg(self):
48 def test_get_repo_autoalias_hg(self):
50 alias = 'hg'
49 alias = 'hg'
51 path = TEST_HG_REPO
50 path = TEST_HG_REPO
52 backend = get_backend(alias)
51 backend = get_backend(alias)
53 repo = backend(safe_str(path))
52 repo = backend(path)
54
53
55 assert repo.__class__ == get_repo(safe_str(path)).__class__
54 assert repo.__class__ == get_repo(path).__class__
56 assert repo.path == get_repo(safe_str(path)).path
55 assert repo.path == get_repo(path).path
57
56
58 def test_get_repo_autoalias_git(self):
57 def test_get_repo_autoalias_git(self):
59 alias = 'git'
58 alias = 'git'
60 path = TEST_GIT_REPO
59 path = TEST_GIT_REPO
61 backend = get_backend(alias)
60 backend = get_backend(alias)
62 repo = backend(safe_str(path))
61 repo = backend(path)
63
62
64 assert repo.__class__ == get_repo(safe_str(path)).__class__
63 assert repo.__class__ == get_repo(path).__class__
65 assert repo.path == get_repo(safe_str(path)).path
64 assert repo.path == get_repo(path).path
66
65
67 def test_get_repo_err(self):
66 def test_get_repo_err(self):
68 blank_repo_path = os.path.join(TESTS_TMP_PATH, 'blank-error-repo')
67 blank_repo_path = os.path.join(TESTS_TMP_PATH, 'blank-error-repo')
General Comments 0
You need to be logged in to leave comments. Login now