Merge pull request #1114 from AndreMiras/feature/python3_cleaning

🗑️ Removes Python 2 constructions
This commit is contained in:
Andre Miras 2020-05-18 23:35:53 +02:00 committed by GitHub
commit 4333b9c048
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 37 additions and 117 deletions

View file

@ -58,19 +58,6 @@ Note that this tool has nothing to do with the eponymous online build service
# edit the buildozer.spec, then
buildozer android debug deploy run
## Installing Buildozer with target Python 2
- Follow the same installation and buildozer init as Python 3
- Make sure the following lines are in your buildozer.spec file.:
# Changes python3 to python2
requirements = python2,kivy
- Finally, build, deploy and run the app on your phone::
buildozer android debug deploy run
## Buildozer Docker image

View file

@ -6,7 +6,7 @@ Generic Python packager for Android / iOS. Desktop later.
'''
__version__ = '1.1.0'
__version__ = '1.1.1.dev0'
import os
import re
@ -26,12 +26,8 @@ from fnmatch import fnmatch
from pprint import pformat
try: # Python 3
from urllib.request import FancyURLopener
from configparser import SafeConfigParser
except ImportError: # Python 2
from urllib import FancyURLopener
from ConfigParser import SafeConfigParser
from urllib.request import FancyURLopener
from configparser import SafeConfigParser
try:
import fcntl
except ImportError:
@ -73,7 +69,6 @@ except ImportError:
LOG_LEVELS_C = (RED, BLUE, BLACK)
LOG_LEVELS_T = 'EID'
SIMPLE_HTTP_SERVER_PORT = 8000
IS_PY3 = sys.version_info[0] >= 3
class ChromeDownloader(FancyURLopener):
@ -101,7 +96,7 @@ class BuildozerCommandException(BuildozerException):
pass
class Buildozer(object):
class Buildozer:
ERROR = 0
INFO = 1
@ -111,7 +106,6 @@ class Buildozer(object):
'deploy', 'run', 'serve')
def __init__(self, filename='buildozer.spec', target=None):
super(Buildozer, self).__init__()
self.log_level = 2
self.environ = {}
self.specfilename = filename
@ -127,10 +121,7 @@ class Buildozer(object):
self.config.getrawdefault = self._get_config_raw_default
if exists(filename):
try:
self.config.read(filename, "utf-8")
except TypeError: # python 2 has no second arg here
self.config.read(filename)
self.config.read(filename, "utf-8")
self.check_configuration_tokens()
# Check all section/tokens for env vars, and replace the
@ -318,10 +309,7 @@ class Buildozer(object):
if get_stdout:
ret_stdout.append(chunk)
if show_output:
if IS_PY3:
stdout.write(chunk.decode('utf-8', 'replace'))
else:
stdout.write(chunk)
stdout.write(chunk.decode('utf-8', 'replace'))
if fd_stderr in readx:
chunk = process.stderr.read()
if not chunk:
@ -329,10 +317,7 @@ class Buildozer(object):
if get_stderr:
ret_stderr.append(chunk)
if show_output:
if IS_PY3:
stderr.write(chunk.decode('utf-8', 'replace'))
else:
stderr.write(chunk)
stderr.write(chunk.decode('utf-8', 'replace'))
stdout.flush()
stderr.flush()
@ -374,10 +359,7 @@ class Buildozer(object):
show_output = kwargs.pop('show_output')
if show_output:
if IS_PY3:
kwargs['logfile'] = codecs.getwriter('utf8')(stdout.buffer)
else:
kwargs['logfile'] = codecs.getwriter('utf8')(stdout)
kwargs['logfile'] = codecs.getwriter('utf8')(stdout.buffer)
if not sensible:
self.debug('Run (expect) {0!r}'.format(command))
@ -571,7 +553,7 @@ class Buildozer(object):
return
self.venv = join(self.buildozer_dir, 'venv')
if not self.file_exists(self.venv):
self.cmd('virtualenv --python=python2.7 ./venv',
self.cmd('python3 -m venv ./venv',
cwd=self.buildozer_dir)
# read virtualenv output and parse it
@ -1073,11 +1055,6 @@ class Buildozer(object):
'''If effective user id is 0, display a warning and require
user input to continue (or to cancel)'''
if IS_PY3:
input_func = input
else:
input_func = raw_input
warn_on_root = self.config.getdefault('buildozer', 'warn_on_root', '1')
try:
euid = os.geteuid() == 0
@ -1090,7 +1067,7 @@ class Buildozer(object):
print('\033[91mThis is \033[1mnot\033[0m \033[91mrecommended, and may lead to problems later.\033[0m')
cont = None
while cont not in ('y', 'n'):
cont = input_func('Are you sure you want to continue [y/n]? ')
cont = input('Are you sure you want to continue [y/n]? ')
if cont == 'n':
sys.exit()

View file

@ -1,6 +1,6 @@
"""
Replacement for shelve, using json.
This is currently needed to correctly support db between Python 2 and 3.
This was needed to correctly support db between Python 2 and 3.
"""
__all__ = ["JsonStore"]
@ -10,12 +10,10 @@ import sys
from json import load, dump, dumps
from os.path import exists
IS_PY3 = sys.version_info[0] >= 3
class JsonStore(object):
class JsonStore:
def __init__(self, filename):
super(JsonStore, self).__init__()
super().__init__()
self.filename = filename
self.data = {}
if exists(filename):
@ -46,10 +44,5 @@ class JsonStore(object):
return self.data.keys()
def sync(self):
# http://stackoverflow.com/questions/12309269/write-json-data-to-file-in-python/14870531#14870531
if IS_PY3:
with open(self.filename, 'w') as fd:
dump(self.data, fd, ensure_ascii=False)
else:
with io.open(self.filename, 'w', encoding='utf-8') as fd:
fd.write(unicode(dumps(self.data, ensure_ascii=False)))
with open(self.filename, 'w') as fd:
dump(self.data, fd, ensure_ascii=False)

View file

@ -11,10 +11,8 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
class Infinity(object):
class Infinity:
def __repr__(self):
return "Infinity"
@ -46,7 +44,7 @@ class Infinity(object):
Infinity = Infinity()
class NegativeInfinity(object):
class NegativeInfinity:
def __repr__(self):
return "-Infinity"

View file

@ -11,8 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import collections
import itertools
import re
@ -49,7 +47,7 @@ class InvalidVersion(ValueError):
"""
class _BaseVersion(object):
class _BaseVersion:
def __hash__(self):
return hash(self._key)

View file

@ -7,9 +7,9 @@ def no_config(f):
return f
class Target(object):
class Target:
def __init__(self, buildozer):
super(Target, self).__init__()
super().__init__()
self.buildozer = buildozer
self.build_mode = 'debug'
self.platform_update = False

View file

@ -27,7 +27,7 @@ import ast
import sh
from pipes import quote
from sys import platform, executable
from buildozer import BuildozerException, USE_COLOR, IS_PY3
from buildozer import BuildozerException, USE_COLOR
from buildozer.target import Target
from os import environ
from os.path import exists, join, realpath, expanduser, basename, relpath
@ -66,7 +66,7 @@ class TargetAndroid(Target):
extra_p4a_args = ''
def __init__(self, *args, **kwargs):
super(TargetAndroid, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._arch = self.buildozer.config.getdefault(
'app', 'android.arch', DEFAULT_ARCH)
self._build_dir = join(
@ -287,7 +287,7 @@ class TargetAndroid(Target):
'[app] "android.permission" contain an unknown'
' permission {0}'.format(permission))
super(TargetAndroid, self).check_configuration_tokens(errors)
super().check_configuration_tokens(errors)
def _get_available_permissions(self):
key = 'android:available_permissions'
@ -917,7 +917,7 @@ class TargetAndroid(Target):
if not entrypoint:
self.buildozer.config.set('app', 'android.entrypoint', 'org.kivy.android.PythonActivity')
super(TargetAndroid, self).cmd_run(*args)
super().cmd_run(*args)
entrypoint = self.buildozer.config.getdefault(
'app', 'android.entrypoint', 'org.kivy.android.PythonActivity')
@ -1312,7 +1312,7 @@ class TargetAndroid(Target):
self.buildozer.cmd(' '.join([self.adb_cmd] + args))
def cmd_deploy(self, *args):
super(TargetAndroid, self).cmd_deploy(*args)
super().cmd_deploy(*args)
state = self.buildozer.state
if 'android:latestapk' not in state:
self.buildozer.error('No APK built yet. Run "debug" first.')

View file

@ -7,7 +7,7 @@ if sys.platform != 'darwin':
raise NotImplementedError('Windows platform not yet working for Android')
import plistlib
from buildozer import BuildozerCommandException, IS_PY3
from buildozer import BuildozerCommandException
from buildozer.target import Target, no_config
from os.path import join, basename, expanduser, realpath
from getpass import getpass
@ -252,14 +252,12 @@ class TargetIos(Target):
self.buildozer.state['ios:latestipa'] = ipa
self.buildozer.state['ios:latestmode'] = self.build_mode
self._create_index()
def cmd_deploy(self, *args):
super(TargetIos, self).cmd_deploy(*args)
super().cmd_deploy(*args)
self._run_ios_deploy(lldb=False)
def cmd_run(self, *args):
super(TargetIos, self).cmd_run(*args)
super().cmd_run(*args)
self._run_ios_deploy(lldb=True)
def cmd_xcode(self, *args):
@ -306,10 +304,6 @@ class TargetIos(Target):
self.app_project_dir, icon_fn),
cwd=self.ios_dir)
def _create_index(self):
# TODO
pass
def check_configuration_tokens(self):
errors = []
config = self.buildozer.config
@ -331,8 +325,7 @@ class TargetIos(Target):
elif identity_release not in available_identities:
errors.append('[app] identity "{}" not found. '
'Check with list_identities'.format(identity_release))
super(TargetIos, self).check_configuration_tokens(errors)
super().check_configuration_tokens(errors)
@no_config
def cmd_list_identities(self, *args):
@ -396,12 +389,7 @@ class TargetIos(Target):
save = None
while save is None:
if IS_PY3:
input_func = input
else:
input_func = raw_input
q = input_func('Do you want to save the password (Y/n): ')
q = input('Do you want to save the password (Y/n): ')
if q in ('', 'Y'):
save = True
elif q == 'n':

View file

@ -15,7 +15,6 @@ import io
from pipes import quote
from sys import platform, executable
from buildozer import BuildozerException
from buildozer import IS_PY3
from buildozer.target import Target
from os import environ
from os.path import (exists, join, realpath, expanduser,

View file

@ -2,11 +2,8 @@ import sys
import unittest
from buildozer import BuildozerCommandException
from buildozer.scripts import client
from unittest import mock
try:
from unittest import mock # Python 3
except ImportError:
import mock # Python 2
class TestClient(unittest.TestCase):

View file

@ -6,11 +6,7 @@ import tempfile
import buildozer as buildozer_module
from buildozer import Buildozer
from buildozer.targets.android import TargetAndroid
try:
from unittest import mock # Python 3
except ImportError:
import mock # Python 2
from unittest import mock
def patch_buildozer(method):
@ -95,9 +91,6 @@ class TestTargetAndroid:
assert self.target_android.p4a_apk_cmd == "apk --debug --bootstrap=sdl2"
assert self.target_android.platform_update is False
@pytest.mark.skipif(
sys.version_info < (3, 0), reason="Python 2 ex_info.value.args is different"
)
def test_init_positional_buildozer(self):
"""Positional `buildozer` argument is required."""
with pytest.raises(TypeError) as ex_info:

View file

@ -3,14 +3,10 @@ import os
import codecs
import unittest
import buildozer as buildozer_module
from buildozer import Buildozer, IS_PY3
from buildozer import Buildozer
from six import StringIO
import tempfile
try:
from unittest import mock # Python 3
except ImportError:
import mock # Python 2
from unittest import mock
from buildozer.targets.android import (
TargetAndroid, DEFAULT_ANDROID_NDK_VERSION, MSG_P4A_RECOMMENDED_NDK_ERROR
@ -201,14 +197,9 @@ class TestBuildozer(unittest.TestCase):
assert stderr is None
assert returncode == 0
# Python2 and Python3 have different approaches for decoding the output
if IS_PY3:
assert m_stdout.write.call_args_list == [
mock.call(command_output.decode('utf-8', 'replace'))
]
else:
assert m_stdout.write.call_args_list == [
mock.call(command_output)
]
assert m_stdout.write.call_args_list == [
mock.call(command_output.decode('utf-8', 'replace'))
]
def test_p4a_recommended_ndk_version_default_value(self):
self.set_specfile_log_level(self.specfile.name, 1)

View file

@ -3,7 +3,6 @@ envlist = pep8,py3
[testenv]
deps =
mock
pytest
py3: coverage
commands = pytest tests/