##// END OF EJS Templates
py3: add safe_str where we really need it to get a str - probably from bytes
Mads Kiilerich -
r8079:1112e440 default
parent child Browse files
Show More
@@ -40,7 +40,7 b' from kallithea.lib.middleware.simplegit '
40 from kallithea.lib.middleware.simplehg import SimpleHg
40 from kallithea.lib.middleware.simplehg import SimpleHg
41 from kallithea.lib.middleware.wrapper import RequestWrapper
41 from kallithea.lib.middleware.wrapper import RequestWrapper
42 from kallithea.lib.utils import check_git_version, load_rcextensions, make_ui, set_app_settings, set_indexer_config, set_vcs_config
42 from kallithea.lib.utils import check_git_version, load_rcextensions, make_ui, set_app_settings, set_indexer_config, set_vcs_config
43 from kallithea.lib.utils2 import str2bool
43 from kallithea.lib.utils2 import safe_str, str2bool
44
44
45
45
46 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
@@ -163,7 +163,7 b' def setup_configuration(app):'
163
163
164 load_rcextensions(root_path=config['here'])
164 load_rcextensions(root_path=config['here'])
165
165
166 repos_path = make_ui().configitems(b'paths')[0][1]
166 repos_path = safe_str(make_ui().configitems(b'paths')[0][1])
167 config['base_path'] = repos_path
167 config['base_path'] = repos_path
168 set_app_settings(config)
168 set_app_settings(config)
169
169
@@ -37,6 +37,7 b' from webob.exc import HTTPBadRequest'
37 from kallithea.lib import helpers as h
37 from kallithea.lib import helpers as h
38 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
38 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
39 from kallithea.lib.base import BaseController, jsonify, render
39 from kallithea.lib.base import BaseController, jsonify, render
40 from kallithea.lib.utils2 import safe_str
40 from kallithea.model.db import RepoGroup, Repository, User, UserGroup
41 from kallithea.model.db import RepoGroup, Repository, User, UserGroup
41 from kallithea.model.repo import RepoModel
42 from kallithea.model.repo import RepoModel
42 from kallithea.model.scm import UserGroupList
43 from kallithea.model.scm import UserGroupList
@@ -116,25 +117,25 b' class HomeController(BaseController):'
116 if _branches:
117 if _branches:
117 res.append({
118 res.append({
118 'text': _('Branch'),
119 'text': _('Branch'),
119 'children': [{'id': rev, 'text': name, 'type': 'branch'} for name, rev in _branches]
120 'children': [{'id': safe_str(rev), 'text': safe_str(name), 'type': 'branch'} for name, rev in _branches]
120 })
121 })
121 _closed_branches = repo.closed_branches.items()
122 _closed_branches = repo.closed_branches.items()
122 if _closed_branches:
123 if _closed_branches:
123 res.append({
124 res.append({
124 'text': _('Closed Branches'),
125 'text': _('Closed Branches'),
125 'children': [{'id': rev, 'text': name, 'type': 'closed-branch'} for name, rev in _closed_branches]
126 'children': [{'id': safe_str(rev), 'text': safe_str(name), 'type': 'closed-branch'} for name, rev in _closed_branches]
126 })
127 })
127 _tags = repo.tags.items()
128 _tags = repo.tags.items()
128 if _tags:
129 if _tags:
129 res.append({
130 res.append({
130 'text': _('Tag'),
131 'text': _('Tag'),
131 'children': [{'id': rev, 'text': name, 'type': 'tag'} for name, rev in _tags]
132 'children': [{'id': safe_str(rev), 'text': safe_str(name), 'type': 'tag'} for name, rev in _tags]
132 })
133 })
133 _bookmarks = repo.bookmarks.items()
134 _bookmarks = repo.bookmarks.items()
134 if _bookmarks:
135 if _bookmarks:
135 res.append({
136 res.append({
136 'text': _('Bookmark'),
137 'text': _('Bookmark'),
137 'children': [{'id': rev, 'text': name, 'type': 'book'} for name, rev in _bookmarks]
138 'children': [{'id': safe_str(rev), 'text': safe_str(name), 'type': 'book'} for name, rev in _bookmarks]
138 })
139 })
139 data = {
140 data = {
140 'more': False,
141 'more': False,
@@ -172,7 +172,7 b' class BasicAuth(paste.auth.basic.AuthBas'
172 (authmeth, auth) = authorization.split(' ', 1)
172 (authmeth, auth) = authorization.split(' ', 1)
173 if 'basic' != authmeth.lower():
173 if 'basic' != authmeth.lower():
174 return self.build_authentication(environ)
174 return self.build_authentication(environ)
175 auth = base64.b64decode(auth.strip())
175 auth = safe_str(base64.b64decode(auth.strip()))
176 _parts = auth.split(':', 1)
176 _parts = auth.split(':', 1)
177 if len(_parts) == 2:
177 if len(_parts) == 2:
178 username, password = _parts
178 username, password = _parts
@@ -538,10 +538,10 b' def _get_header(vcs, diff_chunk):'
538 match = _hg_header_re.match(diff_chunk)
538 match = _hg_header_re.match(diff_chunk)
539 if match is None:
539 if match is None:
540 raise Exception('diff not recognized as valid %s diff' % vcs)
540 raise Exception('diff not recognized as valid %s diff' % vcs)
541 meta_info = match.groupdict()
541 meta_info = {k: None if v is None else safe_str(v) for k, v in match.groupdict().items()}
542 rest = diff_chunk[match.end():]
542 rest = diff_chunk[match.end():]
543 if rest and _header_next_check.match(rest):
543 if rest and _header_next_check.match(rest):
544 raise Exception('cannot parse %s diff header: %r followed by %r' % (vcs, diff_chunk[:match.end()], rest[:1000]))
544 raise Exception('cannot parse %s diff header: %r followed by %r' % (vcs, safe_str(bytes(diff_chunk[:match.end()])), safe_str(bytes(rest[:1000]))))
545 diff_lines = (_escaper(m.group(0)) for m in re.finditer(br'.*\n|.+$', rest)) # don't split on \r as str.splitlines do
545 diff_lines = (_escaper(m.group(0)) for m in re.finditer(br'.*\n|.+$', rest)) # don't split on \r as str.splitlines do
546 return meta_info, diff_lines
546 return meta_info, diff_lines
547
547
@@ -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
37 from kallithea.lib.utils2 import HookEnvironmentError, ascii_str, get_hook_environment, safe_bytes, safe_str
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
@@ -67,7 +67,7 b' def _get_scm_size(alias, root_path):'
67
67
68 def repo_size(ui, repo, hooktype=None, **kwargs):
68 def repo_size(ui, repo, hooktype=None, **kwargs):
69 """Show size of Mercurial repository, to be called after push."""
69 """Show size of Mercurial repository, to be called after push."""
70 size_hg_f, size_root_f, size_total_f = _get_scm_size('.hg', repo.root)
70 size_hg_f, size_root_f, size_total_f = _get_scm_size('.hg', safe_str(repo.root))
71
71
72 last_cs = repo[len(repo) - 1]
72 last_cs = repo[len(repo) - 1]
73
73
@@ -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
43 from kallithea.lib.utils2 import ascii_bytes, aslist, get_current_authuser, safe_bytes, safe_str
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
@@ -586,13 +586,13 b' def check_git_version():'
586 return None
586 return None
587
587
588 if stderr:
588 if stderr:
589 log.warning('Error/stderr from "%s --version":\n%s', settings.GIT_EXECUTABLE_PATH, stderr)
589 log.warning('Error/stderr from "%s --version":\n%s', settings.GIT_EXECUTABLE_PATH, safe_str(stderr))
590
590
591 if not stdout:
591 if not stdout:
592 log.warning('No working git executable found - check "git_path" in the ini file.')
592 log.warning('No working git executable found - check "git_path" in the ini file.')
593 return None
593 return None
594
594
595 output = stdout.strip()
595 output = safe_str(stdout).strip()
596 m = re.search(r"\d+.\d+.\d+", output)
596 m = re.search(r"\d+.\d+.\d+", output)
597 if m:
597 if m:
598 ver = StrictVersion(m.group(0))
598 ver = StrictVersion(m.group(0))
@@ -96,7 +96,7 b' class GitChangeset(BaseChangeset):'
96 @LazyProperty
96 @LazyProperty
97 def branches(self):
97 def branches(self):
98 heads = self.repository._heads(reverse=True)
98 heads = self.repository._heads(reverse=True)
99 return [b for b in heads if heads[b] == self._commit.id] # FIXME: Inefficient ... and returning None!
99 return [safe_str(b) for b in heads if heads[b] == self._commit.id] # FIXME: Inefficient ... and returning None!
100
100
101 def _fix_path(self, path):
101 def _fix_path(self, path):
102 """
102 """
@@ -122,10 +122,9 b' class GitChangeset(BaseChangeset):'
122
122
123 # initially extract things from root dir
123 # initially extract things from root dir
124 for item, stat, id in tree.items():
124 for item, stat, id in tree.items():
125 name = safe_str(item)
125 if curdir:
126 if curdir:
126 name = '/'.join((curdir, item))
127 name = '/'.join((curdir, name))
127 else:
128 name = item
129 self._paths[name] = id
128 self._paths[name] = id
130 self._stat_modes[name] = stat
129 self._stat_modes[name] = stat
131
130
@@ -136,7 +135,8 b' class GitChangeset(BaseChangeset):'
136 curdir = dir
135 curdir = dir
137 dir_id = None
136 dir_id = None
138 for item, stat, id in tree.items():
137 for item, stat, id in tree.items():
139 if dir == item:
138 name = safe_str(item)
139 if dir == name:
140 dir_id = id
140 dir_id = id
141 if dir_id:
141 if dir_id:
142 # Update tree
142 # Update tree
@@ -148,10 +148,9 b' class GitChangeset(BaseChangeset):'
148
148
149 # cache all items from the given traversed tree
149 # cache all items from the given traversed tree
150 for item, stat, id in tree.items():
150 for item, stat, id in tree.items():
151 name = safe_str(item)
151 if curdir:
152 if curdir:
152 name = '/'.join((curdir, item))
153 name = '/'.join((curdir, name))
153 else:
154 name = item
155 self._paths[name] = id
154 self._paths[name] = id
156 self._stat_modes[name] = stat
155 self._stat_modes[name] = stat
157 if path not in self._paths:
156 if path not in self._paths:
@@ -404,10 +403,9 b' class GitChangeset(BaseChangeset):'
404 filenodes = []
403 filenodes = []
405 als = self.repository.alias
404 als = self.repository.alias
406 for name, stat, id in tree.items():
405 for name, stat, id in tree.items():
406 obj_path = safe_str(name)
407 if path != '':
407 if path != '':
408 obj_path = '/'.join((path, name))
408 obj_path = '/'.join((path, obj_path))
409 else:
410 obj_path = name
411 if objects.S_ISGITLINK(stat):
409 if objects.S_ISGITLINK(stat):
412 root_tree = self.repository._repo[self._tree_id]
410 root_tree = self.repository._repo[self._tree_id]
413 cf = ConfigFile.from_file(BytesIO(self.repository._repo.get_object(root_tree[b'.gitmodules'][1]).data))
411 cf = ConfigFile.from_file(BytesIO(self.repository._repo.get_object(root_tree[b'.gitmodules'][1]).data))
@@ -499,11 +497,11 b' class GitChangeset(BaseChangeset):'
499 changes = _r.object_store.tree_changes(oid, _r[self._commit.id].tree)
497 changes = _r.object_store.tree_changes(oid, _r[self._commit.id].tree)
500 for (oldpath, newpath), (_, _), (_, _) in changes:
498 for (oldpath, newpath), (_, _), (_, _) in changes:
501 if newpath and oldpath:
499 if newpath and oldpath:
502 modified.add(newpath)
500 modified.add(safe_str(newpath))
503 elif newpath and not oldpath:
501 elif newpath and not oldpath:
504 added.add(newpath)
502 added.add(safe_str(newpath))
505 elif not newpath and oldpath:
503 elif not newpath and oldpath:
506 deleted.add(oldpath)
504 deleted.add(safe_str(oldpath))
507 return added, modified, deleted
505 return added, modified, deleted
508
506
509 def _get_paths_for_status(self, status):
507 def _get_paths_for_status(self, status):
@@ -359,7 +359,7 b' class GitRepository(BaseRepository):'
359 if not self.revisions:
359 if not self.revisions:
360 return {}
360 return {}
361 sortkey = lambda ctx: ctx[0]
361 sortkey = lambda ctx: ctx[0]
362 _branches = [(key, ascii_str(sha))
362 _branches = [(safe_str(key), ascii_str(sha))
363 for key, (sha, type_) in self._parsed_refs.items() if type_ == b'H']
363 for key, (sha, type_) in self._parsed_refs.items() if type_ == b'H']
364 return OrderedDict(sorted(_branches, key=sortkey, reverse=False))
364 return OrderedDict(sorted(_branches, key=sortkey, reverse=False))
365
365
@@ -376,7 +376,7 b' class GitRepository(BaseRepository):'
376 return {}
376 return {}
377
377
378 sortkey = lambda ctx: ctx[0]
378 sortkey = lambda ctx: ctx[0]
379 _tags = [(key, ascii_str(sha))
379 _tags = [(safe_str(key), ascii_str(sha))
380 for key, (sha, type_) in self._parsed_refs.items() if type_ == b'T']
380 for key, (sha, type_) in self._parsed_refs.items() if type_ == b'T']
381 return OrderedDict(sorted(_tags, key=sortkey, reverse=True))
381 return OrderedDict(sorted(_tags, key=sortkey, reverse=True))
382
382
@@ -418,7 +418,7 b' class GitRepository(BaseRepository):'
418 if name not in self.tags:
418 if name not in self.tags:
419 raise TagDoesNotExistError("Tag %s does not exist" % name)
419 raise TagDoesNotExistError("Tag %s does not exist" % name)
420 # self._repo.refs is a DiskRefsContainer, and .path gives the full absolute path of '.git'
420 # self._repo.refs is a DiskRefsContainer, and .path gives the full absolute path of '.git'
421 tagpath = os.path.join(self._repo.refs.path, 'refs', 'tags', name)
421 tagpath = os.path.join(safe_str(self._repo.refs.path), 'refs', 'tags', name)
422 try:
422 try:
423 os.remove(tagpath)
423 os.remove(tagpath)
424 self._parsed_refs = self._get_parsed_refs()
424 self._parsed_refs = self._get_parsed_refs()
@@ -712,9 +712,10 b' class GitRepository(BaseRepository):'
712
712
713 for config in gen_configs():
713 for config in gen_configs():
714 try:
714 try:
715 return config.get(section, name)
715 value = config.get(section, name)
716 except KeyError:
716 except KeyError:
717 continue
717 continue
718 return None if value is None else safe_str(value)
718 return None
719 return None
719
720
720 def get_user_name(self, config_file=None):
721 def get_user_name(self, config_file=None):
@@ -1,6 +1,6 b''
1 import re
1 import re
2
2
3 from kallithea.lib.utils2 import ascii_str
3 from kallithea.lib.utils2 import ascii_str, safe_str
4 from kallithea.lib.vcs.backends.base import BaseWorkdir
4 from kallithea.lib.vcs.backends.base import BaseWorkdir
5 from kallithea.lib.vcs.exceptions import BranchDoesNotExistError, RepositoryError
5 from kallithea.lib.vcs.exceptions import BranchDoesNotExistError, RepositoryError
6
6
@@ -10,7 +10,7 b' class GitWorkdir(BaseWorkdir):'
10 def get_branch(self):
10 def get_branch(self):
11 headpath = self.repository._repo.refs.refpath(b'HEAD')
11 headpath = self.repository._repo.refs.refpath(b'HEAD')
12 try:
12 try:
13 content = open(headpath).read()
13 content = safe_str(open(headpath, 'rb').read())
14 match = re.match(r'^ref: refs/heads/(?P<branch>.+)\n$', content)
14 match = re.match(r'^ref: refs/heads/(?P<branch>.+)\n$', content)
15 if match:
15 if match:
16 return match.groupdict()['branch']
16 return match.groupdict()['branch']
@@ -121,7 +121,7 b' class MercurialChangeset(BaseChangeset):'
121
121
122 @LazyProperty
122 @LazyProperty
123 def _file_paths(self):
123 def _file_paths(self):
124 return list(self._ctx)
124 return list(safe_str(f) for f in self._ctx)
125
125
126 @LazyProperty
126 @LazyProperty
127 def _dir_paths(self):
127 def _dir_paths(self):
@@ -386,21 +386,21 b' class MercurialChangeset(BaseChangeset):'
386 """
386 """
387 Returns list of added ``FileNode`` objects.
387 Returns list of added ``FileNode`` objects.
388 """
388 """
389 return AddedFileNodesGenerator([n for n in self.status.added], self)
389 return AddedFileNodesGenerator([safe_str(n) for n in self.status.added], self)
390
390
391 @property
391 @property
392 def changed(self):
392 def changed(self):
393 """
393 """
394 Returns list of modified ``FileNode`` objects.
394 Returns list of modified ``FileNode`` objects.
395 """
395 """
396 return ChangedFileNodesGenerator([n for n in self.status.modified], self)
396 return ChangedFileNodesGenerator([safe_str(n) for n in self.status.modified], self)
397
397
398 @property
398 @property
399 def removed(self):
399 def removed(self):
400 """
400 """
401 Returns list of removed ``FileNode`` objects.
401 Returns list of removed ``FileNode`` objects.
402 """
402 """
403 return RemovedFileNodesGenerator([n for n in self.status.removed], self)
403 return RemovedFileNodesGenerator([safe_str(n) for n in self.status.removed], self)
404
404
405 @LazyProperty
405 @LazyProperty
406 def extra(self):
406 def extra(self):
@@ -5,7 +5,7 b' import mercurial.node'
5
5
6 from kallithea.lib.vcs.backends.base import BaseInMemoryChangeset
6 from kallithea.lib.vcs.backends.base import BaseInMemoryChangeset
7 from kallithea.lib.vcs.exceptions import RepositoryError
7 from kallithea.lib.vcs.exceptions import RepositoryError
8 from kallithea.lib.vcs.utils import ascii_str, safe_bytes
8 from kallithea.lib.vcs.utils import ascii_str, safe_bytes, safe_str
9
9
10
10
11 class MercurialInMemoryChangeset(BaseInMemoryChangeset):
11 class MercurialInMemoryChangeset(BaseInMemoryChangeset):
@@ -45,7 +45,7 b' class MercurialInMemoryChangeset(BaseInM'
45 Callback from Mercurial, returning ctx to commit for the given
45 Callback from Mercurial, returning ctx to commit for the given
46 path.
46 path.
47 """
47 """
48 path = bytes_path # will be different for py3
48 path = safe_str(bytes_path)
49
49
50 # check if this path is removed
50 # check if this path is removed
51 if path in (node.path for node in self.removed):
51 if path in (node.path for node in self.removed):
@@ -480,7 +480,7 b' class MercurialRepository(BaseRepository'
480 if name in allowed or self._repo.ui.configbool(b"web",
480 if name in allowed or self._repo.ui.configbool(b"web",
481 b"allow" + name,
481 b"allow" + name,
482 untrusted=True):
482 untrusted=True):
483 yield {"type": name, "extension": ext, "node": archive_name}
483 yield {"type": safe_str(name), "extension": ext, "node": archive_name}
484
484
485 def _get_url(self, url):
485 def _get_url(self, url):
486 """
486 """
@@ -589,7 +589,8 b' class MercurialRepository(BaseRepository'
589 config = mercurial.ui.ui()
589 config = mercurial.ui.ui()
590 for path in config_file:
590 for path in config_file:
591 config.readconfig(safe_bytes(path))
591 config.readconfig(safe_bytes(path))
592 return config.config(safe_bytes(section), safe_bytes(name))
592 value = config.config(safe_bytes(section), safe_bytes(name))
593 return value if value is None else safe_str(value)
593
594
594 def get_user_name(self, config_file=None):
595 def get_user_name(self, config_file=None):
595 """
596 """
@@ -2,13 +2,13 b' import mercurial.merge'
2
2
3 from kallithea.lib.vcs.backends.base import BaseWorkdir
3 from kallithea.lib.vcs.backends.base import BaseWorkdir
4 from kallithea.lib.vcs.exceptions import BranchDoesNotExistError
4 from kallithea.lib.vcs.exceptions import BranchDoesNotExistError
5 from kallithea.lib.vcs.utils import ascii_bytes, ascii_str
5 from kallithea.lib.vcs.utils import ascii_bytes, ascii_str, safe_str
6
6
7
7
8 class MercurialWorkdir(BaseWorkdir):
8 class MercurialWorkdir(BaseWorkdir):
9
9
10 def get_branch(self):
10 def get_branch(self):
11 return self.repository._repo.dirstate.branch()
11 return safe_str(self.repository._repo.dirstate.branch())
12
12
13 def get_changeset(self):
13 def get_changeset(self):
14 wk_dir_id = ascii_str(self.repository._repo[None].parents()[0].hex())
14 wk_dir_id = ascii_str(self.repository._repo[None].parents()[0].hex())
General Comments 0
You need to be logged in to leave comments. Login now