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

View file

@ -1,6 +1,6 @@
""" """
Replacement for shelve, using json. 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"] __all__ = ["JsonStore"]
@ -10,12 +10,10 @@ import sys
from json import load, dump, dumps from json import load, dump, dumps
from os.path import exists from os.path import exists
IS_PY3 = sys.version_info[0] >= 3 class JsonStore:
class JsonStore(object):
def __init__(self, filename): def __init__(self, filename):
super(JsonStore, self).__init__() super().__init__()
self.filename = filename self.filename = filename
self.data = {} self.data = {}
if exists(filename): if exists(filename):
@ -46,10 +44,5 @@ class JsonStore(object):
return self.data.keys() return self.data.keys()
def sync(self): 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: with open(self.filename, 'w') as fd:
dump(self.data, fd, ensure_ascii=False) 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)))

View file

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

View file

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

View file

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

View file

@ -27,7 +27,7 @@ import ast
import sh import sh
from pipes import quote from pipes import quote
from sys import platform, executable 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 buildozer.target import Target
from os import environ from os import environ
from os.path import exists, join, realpath, expanduser, basename, relpath from os.path import exists, join, realpath, expanduser, basename, relpath
@ -66,7 +66,7 @@ class TargetAndroid(Target):
extra_p4a_args = '' extra_p4a_args = ''
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(TargetAndroid, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._arch = self.buildozer.config.getdefault( self._arch = self.buildozer.config.getdefault(
'app', 'android.arch', DEFAULT_ARCH) 'app', 'android.arch', DEFAULT_ARCH)
self._build_dir = join( self._build_dir = join(
@ -287,7 +287,7 @@ class TargetAndroid(Target):
'[app] "android.permission" contain an unknown' '[app] "android.permission" contain an unknown'
' permission {0}'.format(permission)) ' permission {0}'.format(permission))
super(TargetAndroid, self).check_configuration_tokens(errors) super().check_configuration_tokens(errors)
def _get_available_permissions(self): def _get_available_permissions(self):
key = 'android:available_permissions' key = 'android:available_permissions'
@ -917,7 +917,7 @@ class TargetAndroid(Target):
if not entrypoint: if not entrypoint:
self.buildozer.config.set('app', 'android.entrypoint', 'org.kivy.android.PythonActivity') 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( entrypoint = self.buildozer.config.getdefault(
'app', 'android.entrypoint', 'org.kivy.android.PythonActivity') 'app', 'android.entrypoint', 'org.kivy.android.PythonActivity')
@ -1312,7 +1312,7 @@ class TargetAndroid(Target):
self.buildozer.cmd(' '.join([self.adb_cmd] + args)) self.buildozer.cmd(' '.join([self.adb_cmd] + args))
def cmd_deploy(self, *args): def cmd_deploy(self, *args):
super(TargetAndroid, self).cmd_deploy(*args) super().cmd_deploy(*args)
state = self.buildozer.state state = self.buildozer.state
if 'android:latestapk' not in state: if 'android:latestapk' not in state:
self.buildozer.error('No APK built yet. Run "debug" first.') 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') raise NotImplementedError('Windows platform not yet working for Android')
import plistlib import plistlib
from buildozer import BuildozerCommandException, IS_PY3 from buildozer import BuildozerCommandException
from buildozer.target import Target, no_config from buildozer.target import Target, no_config
from os.path import join, basename, expanduser, realpath from os.path import join, basename, expanduser, realpath
from getpass import getpass from getpass import getpass
@ -252,14 +252,12 @@ class TargetIos(Target):
self.buildozer.state['ios:latestipa'] = ipa self.buildozer.state['ios:latestipa'] = ipa
self.buildozer.state['ios:latestmode'] = self.build_mode self.buildozer.state['ios:latestmode'] = self.build_mode
self._create_index()
def cmd_deploy(self, *args): def cmd_deploy(self, *args):
super(TargetIos, self).cmd_deploy(*args) super().cmd_deploy(*args)
self._run_ios_deploy(lldb=False) self._run_ios_deploy(lldb=False)
def cmd_run(self, *args): def cmd_run(self, *args):
super(TargetIos, self).cmd_run(*args) super().cmd_run(*args)
self._run_ios_deploy(lldb=True) self._run_ios_deploy(lldb=True)
def cmd_xcode(self, *args): def cmd_xcode(self, *args):
@ -306,10 +304,6 @@ class TargetIos(Target):
self.app_project_dir, icon_fn), self.app_project_dir, icon_fn),
cwd=self.ios_dir) cwd=self.ios_dir)
def _create_index(self):
# TODO
pass
def check_configuration_tokens(self): def check_configuration_tokens(self):
errors = [] errors = []
config = self.buildozer.config config = self.buildozer.config
@ -331,8 +325,7 @@ class TargetIos(Target):
elif identity_release not in available_identities: elif identity_release not in available_identities:
errors.append('[app] identity "{}" not found. ' errors.append('[app] identity "{}" not found. '
'Check with list_identities'.format(identity_release)) 'Check with list_identities'.format(identity_release))
super().check_configuration_tokens(errors)
super(TargetIos, self).check_configuration_tokens(errors)
@no_config @no_config
def cmd_list_identities(self, *args): def cmd_list_identities(self, *args):
@ -396,12 +389,7 @@ class TargetIos(Target):
save = None save = None
while save is None: while save is None:
if IS_PY3: q = input('Do you want to save the password (Y/n): ')
input_func = input
else:
input_func = raw_input
q = input_func('Do you want to save the password (Y/n): ')
if q in ('', 'Y'): if q in ('', 'Y'):
save = True save = True
elif q == 'n': elif q == 'n':

View file

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

View file

@ -2,11 +2,8 @@ import sys
import unittest import unittest
from buildozer import BuildozerCommandException from buildozer import BuildozerCommandException
from buildozer.scripts import client 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): class TestClient(unittest.TestCase):

View file

@ -6,11 +6,7 @@ import tempfile
import buildozer as buildozer_module import buildozer as buildozer_module
from buildozer import Buildozer from buildozer import Buildozer
from buildozer.targets.android import TargetAndroid from buildozer.targets.android import TargetAndroid
from unittest import mock
try:
from unittest import mock # Python 3
except ImportError:
import mock # Python 2
def patch_buildozer(method): 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.p4a_apk_cmd == "apk --debug --bootstrap=sdl2"
assert self.target_android.platform_update is False 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): def test_init_positional_buildozer(self):
"""Positional `buildozer` argument is required.""" """Positional `buildozer` argument is required."""
with pytest.raises(TypeError) as ex_info: with pytest.raises(TypeError) as ex_info:

View file

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

View file

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