##// END OF EJS Templates
cleanups: typing + whitespaces
super-admin -
r5101:2d193aa6 default
parent child Browse files
Show More
@@ -1,123 +1,127 b''
1 1
2 2 # Copyright (C) 2010-2023 RhodeCode GmbH
3 3 #
4 4 # This program is free software: you can redistribute it and/or modify
5 5 # it under the terms of the GNU Affero General Public License, version 3
6 6 # (only), as published by the Free Software Foundation.
7 7 #
8 8 # This program is distributed in the hope that it will be useful,
9 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 11 # GNU General Public License for more details.
12 12 #
13 13 # You should have received a copy of the GNU Affero General Public License
14 14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 15 #
16 16 # This program is dual-licensed. If you wish to learn more about the
17 17 # RhodeCode Enterprise Edition, including its added features, Support services,
18 18 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 19
20 20
21 21 import random
22 22 import pytest
23 23
24 24 from rhodecode.api.utils import get_origin
25 25 from rhodecode.lib.ext_json import json
26 26
27 27
28 28 def jsonify(obj):
29 29 return json.loads(json.dumps(obj))
30 30
31 31
32 32 API_URL = '/_admin/api'
33 33
34 34
35 35 def assert_call_ok(id_, given):
36 36 expected = jsonify({
37 37 'id': id_,
38 38 'error': None,
39 39 'result': None
40 40 })
41 41 given = json.loads(given)
42 42
43 43 assert expected['id'] == given['id']
44 44 assert expected['error'] == given['error']
45 45 return given['result']
46 46
47 47
48 48 def assert_ok(id_, expected, given):
49 49 given = json.loads(given)
50 50 if given.get('error'):
51 51 err = given['error']
52 52 pytest.fail(f"Unexpected ERROR in expected success response: `{err}`")
53 53
54 54 expected = jsonify({
55 55 'id': id_,
56 56 'error': None,
57 57 'result': expected
58 58 })
59 59
60 60 assert expected == given
61 61
62 62
63 63 def assert_error(id_, expected, given):
64 64 expected = jsonify({
65 65 'id': id_,
66 66 'error': expected,
67 67 'result': None
68 68 })
69 69 given = json.loads(given)
70 70 assert expected == given
71 71
72 72
73 73 def build_data(apikey, method, **kw):
74 74 """
75 75 Builds API data with given random ID
76 76 """
77 77 random_id = random.randrange(1, 9999)
78 78 return random_id, json.dumps({
79 79 "id": random_id,
80 80 "api_key": apikey,
81 81 "method": method,
82 82 "args": kw
83 83 })
84 84
85 85
86 def api_call(app, params, status=None):
86 def api_call(app, params, status=None, assert_no_error=False):
87 87 response = app.post(
88 88 API_URL, content_type='application/json', params=params, status=status,
89 89 headers=[('Content-Type', 'application/json')])
90 if assert_no_error:
91 err_resp = response.json.get('error')
92 if err_resp:
93 raise AssertionError(f'ERROR in response: {err_resp}')
90 94 return response
91 95
92 96
93 97 def crash(*args, **kwargs):
94 98 raise Exception('Total Crash !')
95 99
96 100
97 101 def expected_permissions(object_with_permissions):
98 102 """
99 103 Returns the expected permissions structure for the given object.
100 104
101 105 The object is expected to be a `Repository`, `RepositoryGroup`,
102 106 or `UserGroup`. They all implement the same permission handling
103 107 API.
104 108 """
105 109 permissions = []
106 110 for _user in object_with_permissions.permissions():
107 111 user_data = {
108 112 'name': _user.username,
109 113 'permission': _user.permission,
110 114 'origin': get_origin(_user),
111 115 'type': "user",
112 116 }
113 117 permissions.append(user_data)
114 118
115 119 for _user_group in object_with_permissions.permission_user_groups():
116 120 user_group_data = {
117 121 'name': _user_group.users_group_name,
118 122 'permission': _user_group.permission,
119 123 'origin': get_origin(_user_group),
120 124 'type': "user_group",
121 125 }
122 126 permissions.append(user_group_data)
123 127 return permissions
@@ -1,169 +1,169 b''
1 1 # Copyright (C) 2011-2023 RhodeCode GmbH
2 2 #
3 3 # This program is free software: you can redistribute it and/or modify
4 4 # it under the terms of the GNU Affero General Public License, version 3
5 5 # (only), as published by the Free Software Foundation.
6 6 #
7 7 # This program is distributed in the hope that it will be useful,
8 8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 10 # GNU General Public License for more details.
11 11 #
12 12 # You should have received a copy of the GNU Affero General Public License
13 13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 14 #
15 15 # This program is dual-licensed. If you wish to learn more about the
16 16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18 18
19 19 import typing
20 20 import base64
21 21 import logging
22 22 from unidecode import unidecode
23 23
24 24 import rhodecode
25 25 from rhodecode.lib.type_utils import aslist
26 26
27 27
28 28 log = logging.getLogger(__name__)
29 29
30 30
31 31 def safe_int(val, default=None) -> int:
32 32 """
33 33 Returns int() of val if val is not convertable to int use default
34 34 instead
35 35
36 36 :param val:
37 37 :param default:
38 38 """
39 39
40 40 try:
41 41 val = int(val)
42 42 except (ValueError, TypeError):
43 43 val = default
44 44
45 45 return val
46 46
47 47
48 48 def safe_float(val, default=None) -> float:
49 49 """
50 50 Returns float() of val if val is not convertable to float use default
51 51 instead
52 52
53 53 :param val:
54 54 :param default:
55 55 """
56 56
57 57 try:
58 58 val = float(val)
59 59 except (ValueError, TypeError):
60 60 val = default
61 61
62 62 return val
63 63
64 64
65 def base64_to_str(text) -> str:
65 def base64_to_str(text: str | bytes) -> str:
66 66 return safe_str(base64.encodebytes(safe_bytes(text))).strip()
67 67
68 68
69 69 def get_default_encodings() -> list[str]:
70 70 return aslist(rhodecode.CONFIG.get('default_encoding', 'utf8'), sep=',')
71 71
72 72
73 73 DEFAULT_ENCODINGS = get_default_encodings()
74 74
75 75
76 76 def safe_str(str_, to_encoding=None) -> str:
77 77 """
78 78 safe str function. Does few trick to turn unicode_ into string
79 79
80 80 :param str_: str to encode
81 81 :param to_encoding: encode to this type UTF8 default
82 82 """
83 83 if isinstance(str_, str):
84 84 return str_
85 85
86 86 # if it's bytes cast to str
87 87 if not isinstance(str_, bytes):
88 88 return str(str_)
89 89
90 90 to_encoding = to_encoding or DEFAULT_ENCODINGS
91 91 if not isinstance(to_encoding, (list, tuple)):
92 92 to_encoding = [to_encoding]
93 93
94 94 for enc in to_encoding:
95 95 try:
96 96 return str(str_, enc)
97 97 except UnicodeDecodeError:
98 98 pass
99 99
100 100 return str(str_, to_encoding[0], 'replace')
101 101
102 102
103 103 def safe_bytes(str_, from_encoding=None) -> bytes:
104 104 """
105 105 safe bytes function. Does few trick to turn str_ into bytes string:
106 106
107 107 :param str_: string to decode
108 108 :param from_encoding: encode from this type UTF8 default
109 109 """
110 110 if isinstance(str_, bytes):
111 111 return str_
112 112
113 113 if not isinstance(str_, str):
114 114 raise ValueError(f'safe_bytes cannot convert other types than str: got: {type(str_)}')
115 115
116 116 from_encoding = from_encoding or get_default_encodings()
117 117 if not isinstance(from_encoding, (list, tuple)):
118 118 from_encoding = [from_encoding]
119 119
120 120 for enc in from_encoding:
121 121 try:
122 122 return str_.encode(enc)
123 123 except UnicodeDecodeError:
124 124 pass
125 125
126 126 return str_.encode(from_encoding[0], 'replace')
127 127
128 128
129 129 def ascii_bytes(str_, allow_bytes=False) -> bytes:
130 130 """
131 131 Simple conversion from str to bytes, with assumption that str_ is pure ASCII.
132 132 Fails with UnicodeError on invalid input.
133 133 This should be used where encoding and "safe" ambiguity should be avoided.
134 134 Where strings already have been encoded in other ways but still are unicode
135 135 string - for example to hex, base64, json, urlencoding, or are known to be
136 136 identifiers.
137 137 """
138 138 if allow_bytes and isinstance(str_, bytes):
139 139 return str_
140 140
141 141 if not isinstance(str_, str):
142 142 raise ValueError(f'ascii_bytes cannot convert other types than str: got: {type(str_)}')
143 143 return str_.encode('ascii')
144 144
145 145
146 146 def ascii_str(str_) -> str:
147 147 """
148 148 Simple conversion from bytes to str, with assumption that str_ is pure ASCII.
149 149 Fails with UnicodeError on invalid input.
150 150 This should be used where encoding and "safe" ambiguity should be avoided.
151 151 Where strings are encoded but also in other ways are known to be ASCII, and
152 152 where a unicode string is wanted without caring about encoding. For example
153 153 to hex, base64, urlencoding, or are known to be identifiers.
154 154 """
155 155
156 156 if not isinstance(str_, bytes):
157 157 raise ValueError(f'ascii_str cannot convert other types than bytes: got: {type(str_)}')
158 158 return str_.decode('ascii')
159 159
160 160
161 161 def convert_special_chars(str_) -> str:
162 162 """
163 163 trie to replace non-ascii letters to their ascii representation eg::
164 164
165 165 `ΕΌoΕ‚w` converts into `zolw`
166 166 """
167 167 value = safe_str(str_)
168 168 converted_value = unidecode(value)
169 169 return converted_value
@@ -1,203 +1,202 b''
1
2 1 # Copyright (C) 2010-2023 RhodeCode GmbH
3 2 #
4 3 # This program is free software: you can redistribute it and/or modify
5 4 # it under the terms of the GNU Affero General Public License, version 3
6 5 # (only), as published by the Free Software Foundation.
7 6 #
8 7 # This program is distributed in the hope that it will be useful,
9 8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 10 # GNU General Public License for more details.
12 11 #
13 12 # You should have received a copy of the GNU Affero General Public License
14 13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 14 #
16 15 # This program is dual-licensed. If you wish to learn more about the
17 16 # RhodeCode Enterprise Edition, including its added features, Support services,
18 17 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 18
20 19 # Import early to make sure things are patched up properly
21 20 from setuptools import setup, find_packages, Extension
22 21
23 22 import os
24 23 import re
25 24 import sys
26 25 import pkgutil
27 26 import platform
28 27 import codecs
29 28
30 29 import pip
31 30
32 31 pip_major_version = int(pip.__version__.split(".")[0])
33 32 if pip_major_version >= 20:
34 33 from pip._internal.req import parse_requirements
35 34 from pip._internal.network.session import PipSession
36 35 elif pip_major_version >= 10:
37 36 from pip._internal.req import parse_requirements
38 37 from pip._internal.download import PipSession
39 38 else:
40 39 from pip.req import parse_requirements
41 40 from pip.download import PipSession
42 41
43 42
44 43 def get_package_name(req_object):
45 44 package_name = None
46 45 try:
47 46 from pip._internal.req.constructors import install_req_from_parsed_requirement
48 47 except ImportError:
49 48 install_req_from_parsed_requirement = None
50 49
51 50 # In 20.1 of pip, the requirements object changed
52 51 if hasattr(req_object, 'req'):
53 52 package_name = req_object.req.name
54 53
55 54 if package_name is None:
56 55 if install_req_from_parsed_requirement:
57 56 package = install_req_from_parsed_requirement(req_object)
58 57 package_name = package.req.name
59 58
60 59 if package_name is None:
61 60 # fallback for older pip
62 61 package_name = re.split('===|<=|!=|==|>=|~=|<|>', req_object.requirement)[0]
63 62
64 63 return package_name
65 64
66 65
67 66 if sys.version_info < (3, 10):
68 67 raise Exception('RhodeCode requires Python 3.10 or later')
69 68
70 69 here = os.path.abspath(os.path.dirname(__file__))
71 70
72 71 # defines current platform
73 72 __platform__ = platform.system()
74 73 __license__ = 'AGPLv3, and Commercial License'
75 74 __author__ = 'RhodeCode GmbH'
76 75 __url__ = 'https://code.rhodecode.com'
77 76 is_windows = __platform__ in ('Windows',)
78 77
79 78
80 79 def _get_requirements(req_filename, exclude=None, extras=None):
81 80 extras = extras or []
82 81 exclude = exclude or []
83 82
84 83 try:
85 84 parsed = parse_requirements(
86 85 os.path.join(here, req_filename), session=PipSession())
87 86 except TypeError:
88 87 # try pip < 6.0.0, that doesn't support session
89 88 parsed = parse_requirements(os.path.join(here, req_filename))
90 89
91 90 requirements = []
92 91 for int_req in parsed:
93 92 req_name = get_package_name(int_req)
94 93 if req_name not in exclude:
95 94 requirements.append(req_name)
96 95 return requirements + extras
97 96
98 97
99 98 # requirements extract
100 99 setup_requirements = ['PasteScript']
101 100 install_requirements = _get_requirements(
102 101 'requirements.txt', exclude=['setuptools', 'entrypoints'])
103 102 test_requirements = _get_requirements(
104 103 'requirements_test.txt')
105 104
106 105
107 106 def get_version():
108 107 version = pkgutil.get_data('rhodecode', 'VERSION')
109 108 return version.decode().strip()
110 109
111 110
112 111 # additional files that goes into package itself
113 112 package_data = {
114 113 '': ['*.txt', '*.rst'],
115 114 'configs': ['*.ini'],
116 115 'rhodecode': ['VERSION', 'i18n/*/LC_MESSAGES/*.mo', ],
117 116 }
118 117
119 118 description = 'Source Code Management Platform'
120 119 keywords = ' '.join([
121 120 'rhodecode', 'mercurial', 'git', 'svn',
122 121 'code review',
123 122 'repo groups', 'ldap', 'repository management', 'hgweb',
124 123 'hgwebdir', 'gitweb', 'serving hgweb',
125 124 ])
126 125
127 126
128 127 # README/DESCRIPTION generation
129 128 readme_file = 'README.rst'
130 129 changelog_file = 'CHANGES.rst'
131 130 try:
132 131 long_description = codecs.open(readme_file).read() + '\n\n' + \
133 132 codecs.open(changelog_file).read()
134 133 except IOError as err:
135 134 sys.stderr.write(
136 135 "[WARNING] Cannot find file specified as long_description (%s)\n "
137 136 "or changelog (%s) skipping that file" % (readme_file, changelog_file))
138 137 long_description = description
139 138
140 139
141 140 setup(
142 141 name='rhodecode-enterprise-ce',
143 142 version=get_version(),
144 143 description=description,
145 144 long_description=long_description,
146 145 keywords=keywords,
147 146 license=__license__,
148 147 author=__author__,
149 148 author_email='support@rhodecode.com',
150 149 url=__url__,
151 150 setup_requires=setup_requirements,
152 151 install_requires=install_requirements,
153 152 tests_require=test_requirements,
154 153 zip_safe=False,
155 154 packages=find_packages(exclude=["docs", "tests*"]),
156 155 package_data=package_data,
157 156 include_package_data=True,
158 157 classifiers=[
159 158 'Development Status :: 6 - Mature',
160 159 'Environment :: Web Environment',
161 160 'Intended Audience :: Developers',
162 161 'Operating System :: OS Independent',
163 162 'Topic :: Software Development :: Version Control',
164 163 'License :: OSI Approved :: Affero GNU General Public License v3 or later (AGPLv3+)',
165 164 'Programming Language :: Python :: 3.10',
166 165 ],
167 166 message_extractors={
168 167 'rhodecode': [
169 168 ('**.py', 'python', None),
170 169 ('**.js', 'javascript', None),
171 170 ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}),
172 171 ('templates/**.html', 'mako', {'input_encoding': 'utf-8'}),
173 172 ('public/**', 'ignore', None),
174 173 ]
175 174 },
176 175 paster_plugins=['PasteScript'],
177 176 entry_points={
178 177 'paste.app_factory': [
179 178 'main=rhodecode.config.middleware:make_pyramid_app',
180 179 ],
181 180 'paste.global_paster_command': [
182 181 'ishell=rhodecode.lib.paster_commands.ishell:Command',
183 182 'upgrade-db=rhodecode.lib.paster_commands.upgrade_db:UpgradeDb',
184 183
185 184 'setup-rhodecode=rhodecode.lib.paster_commands.deprecated.setup_rhodecode:Command',
186 185 'celeryd=rhodecode.lib.paster_commands.deprecated.celeryd:Command',
187 186 ],
188 187 'pyramid.pshell_runner': [
189 188 'ipython = rhodecode.lib.pyramid_shell:ipython_shell_runner',
190 189 ],
191 190 'console_scripts': [
192 191 'rc-setup-app=rhodecode.lib.rc_commands.setup_rc:main',
193 192 'rc-upgrade-db=rhodecode.lib.rc_commands.upgrade_db:main',
194 193 'rc-ishell=rhodecode.lib.rc_commands.ishell:main',
195 194 'rc-add-artifact=rhodecode.lib.rc_commands.add_artifact:main',
196 195 'rc-ssh-wrapper=rhodecode.apps.ssh_support.lib.ssh_wrapper:main',
197 196 ],
198 197 'beaker.backends': [
199 198 'memorylru_base=rhodecode.lib.memory_lru_dict:MemoryLRUNamespaceManagerBase',
200 199 'memorylru_debug=rhodecode.lib.memory_lru_dict:MemoryLRUNamespaceManagerDebug'
201 200 ]
202 201 },
203 202 )
General Comments 0
You need to be logged in to leave comments. Login now