From 0b1cb838ae21ad5d82883ca2ea9003bd413e4137 Mon Sep 17 00:00:00 2001 From: Sundeep Anand Date: Tue, 19 Jan 2016 15:00:04 +0530 Subject: [PATCH 1/3] python2.7 check --- setup.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/setup.py b/setup.py index 031a79e..db6c5e9 100755 --- a/setup.py +++ b/setup.py @@ -3,6 +3,7 @@ Build script for zanata-python-client """ from setuptools import setup, find_packages +import sys import os import subprocess @@ -40,6 +41,9 @@ def get_client_version(): return number +assert sys.version_info >= (2, 7), ( + "Only Python 2.7 and later is supported by zanata-python-client.") + setup( name="zanata-python-client", version=get_client_version(), @@ -77,5 +81,6 @@ def get_client_version(): 'License :: OSI Approved :: GNU Lesser General Public License (LGPL)', 'Operating System :: Unix', 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', ], ) From 029d166bc5178fdebf2de2b2928724eb5388d1a3 Mon Sep 17 00:00:00 2001 From: Sundeep Anand Date: Wed, 20 Jan 2016 20:10:46 +0530 Subject: [PATCH 2/3] backport --- .travis.yml | 5 +- Makefile | 2 +- requirements-dev.txt | 13 +++ requirements.txt | 15 +-- setup.py | 17 +-- test/test_context.py | 15 ++- test/test_parseconfig.py | 2 +- test/test_service.py | 9 +- zanataclient/__init__.py | 6 +- zanataclient/cmdbase.py | 50 ++++----- zanataclient/command.py | 54 ++++----- zanataclient/context.py | 17 +-- zanataclient/csvconverter.py | 6 +- zanataclient/initcmd.py | 44 +++++--- zanataclient/parseconfig.py | 16 +-- zanataclient/publicanutil.py | 8 +- zanataclient/pullcmd.py | 18 +-- zanataclient/pushcmd.py | 20 ++-- zanataclient/zanata.py | 60 +++++----- zanataclient/zanatacmd.py | 129 +++++++++++----------- zanataclient/zanatalib/__init__.py | 14 +-- zanataclient/zanatalib/docservice.py | 2 +- zanataclient/zanatalib/glossaryservice.py | 2 +- zanataclient/zanatalib/logger.py | 12 +- zanataclient/zanatalib/projectservice.py | 14 +-- zanataclient/zanatalib/projectutils.py | 8 +- zanataclient/zanatalib/resource.py | 10 +- zanataclient/zanatalib/rest/__init__.py | 2 +- zanataclient/zanatalib/rest/client.py | 38 ++++--- zanataclient/zanatalib/rest/config.py | 52 +++++---- zanataclient/zanatalib/statservice.py | 2 +- zanataclient/zanatalib/versionservice.py | 2 +- 32 files changed, 352 insertions(+), 312 deletions(-) create mode 100644 requirements-dev.txt diff --git a/.travis.yml b/.travis.yml index fd959c1..1774785 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,10 @@ language: python python: + - "2.4" + - "2.5" + - "2.6" - "2.7" # command to install dependencies -install: "pip install -r requirements.txt" +install: "pip install -r requirements-dev.txt" # command to run tests script: make flake8 test diff --git a/Makefile b/Makefile index 78ade81..db3b262 100644 --- a/Makefile +++ b/Makefile @@ -26,7 +26,7 @@ lint-report: pylint --reports=n zanata zanataclient flake8: - flake8 --ignore=E501,F403,W601,F841,F401,E711,E712 zanataclient test + flake8 --ignore=E501,F403,F841,F401 zanataclient test test: (cd test; python test_all.py) diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..b82f79e --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,13 @@ +-r requirements.txt +flake8==2.4.1 +funcsigs==0.4 +linecache2==1.0.0 +mccabe==0.3.1 +MiniMock==1.2.8 +mock==1.3.0 +pbr==1.8.1 +pep8==1.5.7 +pyflakes==0.8.1 +six==1.10.0 +traceback2==1.4.0 +unittest2==1.1.0 diff --git a/requirements.txt b/requirements.txt index 3761389..615c005 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,3 @@ -flake8==2.4.1 -funcsigs==0.4 -httplib2==0.9.2 -ipdb==0.8.1 -mccabe==0.3.1 -MiniMock==1.2.8 -mock==1.3.0 -pbr==1.8.1 -pep8==1.5.7 -polib==1.0.7 -pyflakes==0.8.1 -six==1.10.0 +httplib2 +polib +ordereddict diff --git a/setup.py b/setup.py index db6c5e9..556f04a 100755 --- a/setup.py +++ b/setup.py @@ -3,11 +3,15 @@ Build script for zanata-python-client """ from setuptools import setup, find_packages -import sys import os import subprocess +def read(fname): + return (open(os.path.join(os.path.dirname(__file__), fname), 'rb') + .read().decode('utf-8')) + + def get_client_version(): number = "" path = os.path.dirname(os.path.realpath(__file__)) @@ -41,18 +45,16 @@ def get_client_version(): return number -assert sys.version_info >= (2, 7), ( - "Only Python 2.7 and later is supported by zanata-python-client.") +requirements = read('requirements.txt').splitlines() + [ + 'setuptools', +] setup( name="zanata-python-client", version=get_client_version(), packages=find_packages(), include_package_data=True, - install_requires=[ - 'polib', - 'httplib2' - ], + install_requires=requirements, description="Zanata Python Client.", author='Jian Ni, Ding-Yi Chen, Anish Patil', author_email='jni@redhat.com, dchen@redhat.com, apatil@redhat.com', @@ -81,6 +83,5 @@ def get_client_version(): 'License :: OSI Approved :: GNU Lesser General Public License (LGPL)', 'Operating System :: Unix', 'Programming Language :: Python', - 'Programming Language :: Python :: 2.7', ], ) diff --git a/test/test_context.py b/test/test_context.py index b9e66d5..40ffdae 100644 --- a/test/test_context.py +++ b/test/test_context.py @@ -71,8 +71,11 @@ def setUp(self): self.init_context = ProjectContext(command_options, 'init') def test_command_options(self): - command_options_keys = ['project_type', 'comment_cols', 'user_config', 'project_config'] - self.assertEqual(self.context.command_options.keys(), command_options_keys) + command_options_keys = ['project_type', 'project_config', 'comment_cols', 'user_config'] + self.assertTrue(list(self.context.command_options.keys())[0] in command_options_keys) + self.assertTrue(list(self.context.command_options.keys())[1] in command_options_keys) + self.assertTrue(list(self.context.command_options.keys())[2] in command_options_keys) + self.assertTrue(list(self.context.command_options.keys())[3] in command_options_keys) self.assertEqual( self.context.command_dict, {'project_config': './testfiles/zanata.xml', 'comment_cols': 'en-US,es,pos,description', @@ -94,8 +97,8 @@ def test_build_local_config(self): self.context.local_config['http_headers'], {'Accept': 'application/json', 'X-Auth-User': 'username', 'X-Auth-Token': 'key'} ) - self.assertIn('client_version', self.context.local_config, - 'local_config should contain client_version') + self.assertTrue('client_version' in self.context.local_config, + 'local_config should contain client_version') @mock.patch('zanataclient.zanatalib.projectservice.LocaleService.get_locales') @mock.patch('zanataclient.zanatalib.versionservice.VersionService.get_server_version') @@ -163,8 +166,8 @@ def test_process_locales(self): def test_init_context(self): context_data = self.init_context.get_context_data() - self.assertIn('servers', context_data) - self.assertIn('http://localhost:8080/zanata', context_data['servers']) + self.assertTrue('servers' in context_data) + self.assertTrue('http://localhost:8080/zanata' in context_data['servers']) if __name__ == '__main__': unittest.main() diff --git a/test/test_parseconfig.py b/test/test_parseconfig.py index ab64e80..018df71 100644 --- a/test/test_parseconfig.py +++ b/test/test_parseconfig.py @@ -41,7 +41,7 @@ def test_user_config(self): user_name = self.config.get_config_value("username", 'servers', server) apikey = self.config.get_config_value("key", 'servers', server) servers = self.config.get_servers() - self.assertIn('http://localhost:8080/zanata', servers) + self.assertTrue('http://localhost:8080/zanata' in servers) self.assertEqual(server, "local") self.assertEqual(user_name, "username") self.assertEqual(apikey, "key") diff --git a/test/test_service.py b/test/test_service.py index 0aa7443..4c71143 100644 --- a/test/test_service.py +++ b/test/test_service.py @@ -23,11 +23,14 @@ "ServiceTest", ) -import unittest import sys import os sys.path.insert(0, os.path.abspath(__file__ + "/../..")) from zanataclient.zanatalib.service import Service +if sys.version_info < (2, 7): + import unittest2 as unittest +else: + import unittest # test data @@ -66,6 +69,10 @@ def test_messages_status_201(self): result_set = self.service.messages(SERVICE_RESPONSE_201, RESPONSE_CONTENT) self.assertTrue(result_set) + @unittest.skipIf( + sys.version_info < (2, 7), + 'https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises' + ) def test_messages_status_401_503(self): with self.assertRaises(SystemExit): self.service.messages(SERVICE_RESPONSE_401, RESPONSE_CONTENT) diff --git a/zanataclient/__init__.py b/zanataclient/__init__.py index 1e3dadc..6ac4b6c 100644 --- a/zanataclient/__init__.py +++ b/zanataclient/__init__.py @@ -20,6 +20,6 @@ # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. -from parseconfig import * -from publicanutil import * -from zanata import * +from .parseconfig import * +from .publicanutil import * +from .zanata import * diff --git a/zanataclient/cmdbase.py b/zanataclient/cmdbase.py index 05ffce3..22e7b0f 100644 --- a/zanataclient/cmdbase.py +++ b/zanataclient/cmdbase.py @@ -24,10 +24,10 @@ import sys import string -from zanatalib.error import NoSuchFileException -from zanatacmd import ZanataCommand -from publicanutil import PublicanUtility -from zanatalib.logger import Logger +from .zanatalib.error import NoSuchFileException +from .zanatacmd import ZanataCommand +from .publicanutil import PublicanUtility +from .zanatalib.logger import Logger log = Logger() @@ -38,7 +38,7 @@ class CommandsInit(object): def __init__(self, *args, **kargs): for name, val in zip(self._fields, args): setattr(self, name, val) - for key, value in kargs.iteritems(): + for key, value in kargs.items(): setattr(self, key, value) def check_essential(self, item, message): @@ -61,7 +61,7 @@ def create_zanatacmd(self): self.context_data.get('url'), self.context_data.get('http_headers') ) - if self.context_data.has_key('disablesslcert'): + if 'disablesslcert' in self.context_data: zanatacmd.disable_ssl_cert_validation() return zanatacmd @@ -190,7 +190,7 @@ def run(self): if lang in locale_map: lang = locale_map[lang] - if self.context_data.has_key('sourcecomments'): + if 'sourcecomments' in self.context_data: sourcecomments = True else: sourcecomments = False @@ -261,8 +261,8 @@ def __init__(self, *args, **kargs): self.plural_support = self.check_plural_support(server_version) self.log_message(self.project_id, self.version_id, username) self.zanatacmd.verify_project(self.project_id, self.version_id) - if self.context_data.has_key('copytrans'): - if self.context_data.has_key('nocopytrans'): + if 'copytrans' in self.context_data: + if 'nocopytrans' in self.context_data: log.error("--copytrans option cannot be used with --no-copytrans. Aborting.") sys.exit(1) else: @@ -283,7 +283,7 @@ def get_files(self): log.error("The project type is not correct, please use 'podir' and 'gettext' as project type") sys.exit(1) - if self.context_data.has_key('srcfile'): + if 'srcfile' in self.context_data: if project_type == 'gettext': tmlfolder, import_file = self.process_srcfile() filelist.append(import_file) @@ -297,7 +297,7 @@ def get_files(self): try: full_path = self.search_file(tmlfolder, self.args[0]) filelist.append(full_path) - except NoSuchFileException, e: + except NoSuchFileException as e: log.error(e.msg) sys.exit(1) else: @@ -314,7 +314,7 @@ def get_files(self): def process_merge(self): merge = "" - if self.context_data.has_key('merge'): + if 'merge' in self.context_data: merge = self.context_data.get('merge') if merge != 'auto' and merge != 'import': log.info("merge option %s is not recognized, assuming default value 'auto'" % merge) @@ -328,9 +328,9 @@ def process_merge(self): def get_lang_list(self): lang_list = [] - if self.context_data.has_key('lang'): + if 'lang' in self.context_data: lang_list = self.context_data.get('lang').split(',') - elif self.context_data.has_key('locale_map'): + elif 'locale_map' in self.context_data: lang_list = self.context_data.get('locale_map').keys() else: log.error("Please specify the language with '--lang' option or in zanata.xml") @@ -341,9 +341,9 @@ def get_lang_list(self): def process_srcdir_withsub(self): tmlfolder = "" - if self.context_data.has_key('srcdir'): + if 'srcdir' in self.context_data: tmlfolder = self.context_data.get('srcdir') - elif self.context_data.has_key('dir'): + elif 'dir' in self.context_data: # Keep dir option for publican/po push tmlfolder = self.context_data.get('dir') else: @@ -360,7 +360,7 @@ def process_srcdir_withsub(self): def process_srcdir(self): tmlfolder = "" - if self.context_data.has_key('srcdir'): + if 'srcdir' in self.context_data: tmlfolder = self.context_data.get('srcdir') else: tmlfolder = os.path.abspath(os.getcwd()) @@ -372,7 +372,7 @@ def process_srcfile(self): tmlfolder = "" file_path = "" - if self.context_data.has_key('srcfile'): + if 'srcfile' in self.context_data: path = self.context_data.get('srcfile') file_path = os.path.abspath(path) tmlfolder = file_path[0:file_path.rfind('/')] @@ -382,7 +382,7 @@ def process_srcfile(self): def process_transdir(self, src_folder): trans_folder = "" - if self.context_data.has_key('transdir'): + if 'transdir' in self.context_data: trans_folder = self.context_data.get('transdir') elif src_folder: trans_folder = src_folder @@ -393,7 +393,7 @@ def process_transdir(self, src_folder): return trans_folder def create_outpath(self, output_folder): - if self.context_data.has_key('transdir'): + if 'transdir'in self.context_data: output = self.context_data.get('transdir') elif output_folder: output = output_folder @@ -419,7 +419,7 @@ def search_file(self, path, filename): raise NoSuchFileException('Error 404', 'File %s not found' % filename) def check_plural_support(self, server_version): - if server_version == None: + if not server_version: return False version = str(server_version.split('-')[0]) @@ -434,9 +434,9 @@ def check_plural_support(self, server_version): def get_importpo(self): importpo = False - if self.context_data.has_key('importpo'): + if 'importpo' in self.context_data: importpo = True - elif self.context_data.has_key('pushtrans'): + elif 'pushtrans' in self.context_data: importpo = True log.info("please use --import-po for old publican push command") @@ -445,9 +445,9 @@ def get_importpo(self): def get_pushtrans(self): pushtrans = False - if self.context_data.has_key('pushtrans'): + if 'pushtrans' in self.context_data: pushtrans = True - elif self.context_data.has_key('importpo'): + elif 'importpo' in self.context_data: pushtrans = True log.info("--import-po option is deprecated, please use '--push-type both' instead") diff --git a/zanataclient/command.py b/zanataclient/command.py index fcb2774..56cdf8f 100644 --- a/zanataclient/command.py +++ b/zanataclient/command.py @@ -84,9 +84,9 @@ def extract_metavars(list_of_option_sets): for option_set in list_of_option_sets: for internal_name, option_list in option_set.items(): for option in option_list: - if option.has_key('metavar'): + if 'metavar' in option: metavar = option['metavar'] - if metavars.has_key(metavar): + if metavar in metavars: if metavars[metavar][1] != option['value']: raise getopt.GetoptError( 'The options %r and %r must have the same ' @@ -145,13 +145,13 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): ) ) # Now set up the long and short options - if option.has_key('short'): + if 'short' in option: for short in option['short']: - if option.has_key('metavar'): + if 'metavar' in option: short_options += short.strip(':-') + ':' else: short_options += short.strip(':-') - if by_option.has_key(short.strip(':')): + if short.strip(':') in by_option: raise OptionConfigurationError( 'The short option %r is already being used' % short ) @@ -160,11 +160,11 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): new['name'] = short.strip(':') by_option[short.strip(':')] = new for longopt in option['long']: - if option.has_key('metavar'): + if 'metavar' in option: long_options.append(longopt.strip('-=') + '=') else: long_options.append(longopt.strip('-=')) - if by_option.has_key(longopt.strip('=')): + if longopt.strip('=') in by_option: raise OptionConfigurationError( 'The long option %r is already being used' % longopt ) @@ -185,7 +185,7 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): internal = by_option[opt[0]]['internal'] new = by_option[opt[0]].copy() new['value'] = opt[1] - if program_options.has_key(internal): + if internal in program_options: program_options[internal].append(new) else: program_options[internal] = [new] @@ -207,10 +207,10 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): command = orig_command + '_' + sub[0] args = sub[1:] else: - print "Unknown command!" + print("Unknown command!") sys.exit(1) else: - print "Please complete the command!" + print("Please complete the command!") sys.exit(1) if orig_command == name and not subcmd: @@ -218,7 +218,7 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): args = sub if not command: - print "Unknown command!" + print("Unknown command!") sys.exit(1) # Get the extra data about the options used this time: @@ -233,7 +233,7 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): internal = by_option[opt[0]]['internal'] new = by_option[opt[0]].copy() new['value'] = opt[1] - if all_options.has_key(internal): + if internal in all_options: all_options[internal].append(new) else: all_options[internal] = [new] @@ -241,7 +241,7 @@ def _parse_command_line(option_sets, subcmds=None, sys_args=None): if option_types['shared']: for k, vs in option_types['shared'].items(): for v in vs: - if option_types['command'].has_key(k): + if k in option_types['command']: option_types['command'][k].append(v) else: option_types['command'][k] = [v] @@ -290,22 +290,22 @@ def handle_program( if existing is None: existing = {} # First, are they asking for program help? - if program_options.has_key('help'): + if 'help' in program_options: # if so provide it no matter what other options are given if help and hasattr(help, '__program__'): - print strip_docstring( + print(strip_docstring( help.__program__ % { 'program': program_name, } - ) + )) else: - print strip_docstring( + print(strip_docstring( handle_program.__doc__ % { 'program': program_name, } - ) + )) sys.exit(0) - elif program_options.has_key('client_version'): + elif 'client_version' in program_options: # Retrieve the version of client version_number = "" path = os.path.dirname(os.path.realpath(__file__)) @@ -316,31 +316,31 @@ def handle_program( version.close() version_number = client_version.rstrip().strip('version: ') except IOError: - print "Please run VERSION-GEN or 'make install' to generate VERSION-FILE" + print("Please run VERSION-GEN or 'make install' to generate VERSION-FILE") version_number = "UNKNOWN" - print "zanata python client version: %s" % version_number + print("zanata python client version: %s" % version_number) else: if not command: raise getopt.GetoptError("No command specified.") # Are they asking for command help: - if command_options.has_key('help'): + if 'help' in command_options: # if so provide it no matter what other options are given - if not command_handler_factories.has_key(command): + if command not in command_handler_factories: raise getopt.GetoptError('No such command %r' % command) if hasattr(help, command): - print strip_docstring( + print(strip_docstring( getattr(help, command) % { 'program': program_name, } - ) + )) else: fn = command_handler_factories[command]() - print strip_docstring( + print(strip_docstring( (fn.__doc__ or 'No help') % { 'program': program_name, } - ) + )) sys.exit(0) # Now handle the command options and arguments diff --git a/zanataclient/context.py b/zanataclient/context.py index 3707d16..667d07b 100644 --- a/zanataclient/context.py +++ b/zanataclient/context.py @@ -27,16 +27,17 @@ import re import os import sys +import functools -from zanatalib.logger import Logger -from parseconfig import ZanataConfig -from zanatalib.error import ( +from .zanatalib.logger import Logger +from .parseconfig import ZanataConfig +from .zanatalib.error import ( UnAvaliableResourceException, UnavailableServiceError ) -from zanatalib.projectservice import ( +from .zanatalib.projectservice import ( LocaleService, IterationService ) -from zanatalib.versionservice import VersionService +from .zanatalib.versionservice import VersionService log = Logger() @@ -138,7 +139,7 @@ def _update_user_config(self): self.local_config.update({'user_name': user_name, 'key': apikey}) log.info("zanata server: %s" % self.get_url()) return True - except Exception, e: + except Exception as e: log.error("Processing user-config file: %s" % str(e)) break break @@ -187,7 +188,7 @@ def _update_server_version(self): """ version = VersionService(self.get_url(), self.local_config.get('http_headers')) - if self.command_dict.has_key('disablesslcert'): + if 'disablesslcert' in self.command_dict: version.disable_ssl_cert_validation() try: @@ -291,7 +292,7 @@ def get_context_data(self): [method() for method in build_configs] # lowest to higest precedence = [self.remote_config, self.local_config, self.command_dict] - context_data = reduce( + context_data = functools.reduce( lambda option, value: dict(option.items() + value.items()), precedence ) return self.filter_context_data(context_data) diff --git a/zanataclient/csvconverter.py b/zanataclient/csvconverter.py index aad1fe6..8cb8ac0 100644 --- a/zanataclient/csvconverter.py +++ b/zanataclient/csvconverter.py @@ -33,7 +33,7 @@ except ImportError: import simplejson as json -from zanatalib.logger import Logger +from .zanatalib.logger import Logger class CSVConverter: @@ -94,8 +94,8 @@ def convert_to_json(self, filepath, locale_map, comments_header): csv_locales_len = len(csv_locales) comments_len = len(comments) if glossary_len != csv_locales_len + comments_len: - print "Wrong entries in csv file, please check your csv file" - print "Entry in csv file", item + print("Wrong entries in csv file, please check your csv file") + print("Entry in csv file", item) sys.exit(1) glossary_comments = item[-2:] for j in range(csv_locales_len): diff --git a/zanataclient/initcmd.py b/zanataclient/initcmd.py index 1d44d40..e640f21 100644 --- a/zanataclient/initcmd.py +++ b/zanataclient/initcmd.py @@ -24,20 +24,28 @@ import sys import fnmatch from datetime import datetime -from collections import OrderedDict +try: + from collections import OrderedDict +except ImportError: + from ordereddict import OrderedDict -from cmdbase import ( +from .cmdbase import ( CommandsInit, CommandsBase ) -from context import ContextBase -from parseconfig import ZanataConfig -from zanatalib.logger import( +from .context import ContextBase +from .parseconfig import ZanataConfig +from .zanatalib.logger import( Logger, TextColour ) -from zanatalib.projectutils import ToolBox +from .zanatalib.projectutils import ToolBox log = Logger() +try: + input = raw_input +except NameError: + pass + class ZanataInit(CommandsInit, ContextBase): """ @@ -88,7 +96,7 @@ def print_options(self, header, options, message, filter_mode=None): counter += 1 counter_dict.update({str(counter): option}) self.ptxt('info_blue', "\t%s) %s" % (str(counter), option)) - choice = raw_input(message) + choice = input(message) while choice not in counter_dict: if filter_mode: filtered_options = filter( @@ -98,13 +106,13 @@ def print_options(self, header, options, message, filter_mode=None): return self.print_options(header, filtered_options, message, True) else: self.ptxt('alert', "Expecting %s but got: %s" % (str(counter_dict.keys()), choice)) - choice = raw_input(message) + choice = input(message) return counter_dict[choice] def print_yes_no(self, message): - yes_no = raw_input(message) + yes_no = input(message) while yes_no not in ('y', 'n', 'Y', 'N'): - yes_no = raw_input(message) + yes_no = input(message) return yes_no in ('y', 'Y') def update_server_url(self): @@ -137,7 +145,7 @@ def set_zanata_command(self): ) def _choose_from_existing_projects(self): - projects_dict = {project.id: project.name for project in self.zanata_cmd.get_projects()} + projects_dict = dict((project.id, project.name) for project in self.zanata_cmd.get_projects()) project_choice = self.print_options( "\n\t======= Available project(s): ID (name) ======", ['%s %s%s%s' % (id, '(', name, ')') for id, name in projects_dict.items()], @@ -153,10 +161,10 @@ def _create_new_project(self): print("Refer to http://zanata.org/help/projects/create-project/ for help.") print("Project ID must start and end with letter or number, and contain only " "letters, numbers, underscores and hyphens.") - input_project_id = raw_input("[?] What ID should your project have? ") - input_project_name = raw_input("[?] What display name should your project have? ") - input_project_desc = raw_input("[?] What discription should your project have? ") - input_project_type = raw_input("[?] What is your project type (gettext, podir)? ") + input_project_id = input("[?] What ID should your project have? ") + input_project_name = input("[?] What display name should your project have? ") + input_project_desc = input("[?] What discription should your project have? ") + input_project_type = input("[?] What is your project type (gettext, podir)? ") project_type = input_project_type if input_project_type in ('gettext', 'podir') \ else 'IterationProject' try: @@ -202,7 +210,7 @@ def _choose_from_existing_versions(self): log.info('Now working with version: %s' % version_choice) def _create_new_version(self): - input_version_id = raw_input("[?] What ID should your version have: ") + input_version_id = input("[?] What ID should your version have: ") try: log.info("Creating version on the server...") if not self.zanata_cmd.create_version(self.local_config.get('project_id'), @@ -278,11 +286,11 @@ def print_dir_contents(self, directory, mode, transdir): self.print_trans_matches(match, locale, transdir) def input_dirs(self, message, mode): - input_dir = raw_input(message) + input_dir = input(message) while not (input_dir and os.path.isdir(os.path.curdir + '/' + input_dir)): self.ptxt('alert', "Directory %s does not exist! Please re-enter." % input_dir) if input_dir \ else self.ptxt('alert', "Can not have blank answer. Please try again.") - input_dir = raw_input(message) + input_dir = input(message) if mode == 'target' and self.local_config.get('srcdir'): list_dir = self.local_config['srcdir'] else: diff --git a/zanataclient/parseconfig.py b/zanataclient/parseconfig.py index 427415c..d4c716f 100644 --- a/zanataclient/parseconfig.py +++ b/zanataclient/parseconfig.py @@ -23,11 +23,13 @@ "ZanataConfig", ) -import ConfigParser import os.path -from zanatalib.logger import Logger +from .zanatalib.logger import Logger from xml.dom import minidom - +try: + from ConfigParser import ConfigParser +except ImportError: + from configparser import ConfigParser project_config = {} @@ -38,7 +40,7 @@ def __init__(self): self._config = "" def set_userconfig(self, path): - self.configparser = ConfigParser.ConfigParser() + self.configparser = ConfigParser() self._config = self.configparser.read(['zanata.ini', path]) def get_server(self, url): @@ -55,7 +57,7 @@ def get_server(self, url): if url == address: server = item[0][:-4] return server - except ConfigParser.NoOptionError, ConfigParser.NoSectionError: + except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): raise else: return None @@ -69,7 +71,7 @@ def get_servers(self): if 'url' in item[0]: servers.append(item[1]) return servers - except ConfigParser.NoOptionError, ConfigParser.NoSectionError: + except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): raise else: return None @@ -79,7 +81,7 @@ def get_config_value(self, name, section, server): try: value = self.configparser.get(section, server + '.' + name) return value - except ConfigParser.NoOptionError, ConfigParser.NoSectionError: + except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): raise else: return None diff --git a/zanataclient/publicanutil.py b/zanataclient/publicanutil.py index 4e3c346..2ec4eed 100644 --- a/zanataclient/publicanutil.py +++ b/zanataclient/publicanutil.py @@ -35,7 +35,7 @@ import simplejson as json import sys -from zanatalib.logger import Logger +from .zanatalib.logger import Logger class PublicanUtility: @@ -208,7 +208,7 @@ def create_extensions(self, pofile, object_type): entry = {"key": item[0], "value": item[1]} entries.append(entry) - if pofile.metadata.has_key('Content-Type'): + if 'Content-Type' in pofile.metadata: self.validate_content_type(pofile.metadata['Content-Type'], object_type) extensions = [{"object-type": object_type, "comment": pofile.header, "entries": entries}] @@ -221,7 +221,7 @@ def create_pofile(self, path): """ try: po = polib.pofile(path) - except Exception, e: + except Exception as e: self.log.error(str(e)) sys.exit(1) @@ -383,7 +383,7 @@ def save_to_pofile(self, path, translations, potcontent, create_skeletons, local po.metadata[item['key']] = item['value'] # specify Content-Type charset to UTF-8 pattern = r'charset=[^;]*' - if po.metadata.has_key('Content-Type'): + if 'Content-Type' in po.metadata: re.sub(pattern, "charset=UTF-8", po.metadata['Content-Type']) else: po.metadata['Content-Type'] = "text/plain; charset=UTF-8" diff --git a/zanataclient/pullcmd.py b/zanataclient/pullcmd.py index 8b3183a..98b4b2a 100644 --- a/zanataclient/pullcmd.py +++ b/zanataclient/pullcmd.py @@ -24,8 +24,8 @@ import sys import string -from zanatalib.logger import Logger -from pushcmd import PushPull +from .zanatalib.logger import Logger +from .pushcmd import PushPull log = Logger() @@ -44,7 +44,7 @@ def run(self): # list the files in project try: filelist = self.zanatacmd.get_file_list(self.project_id, self.version_id) - except Exception, e: + except Exception as e: log.error(str(e)) sys.exit(1) @@ -53,25 +53,25 @@ def run(self): if self.context_data.get('publican_po'): # Keep dir option for publican/po pull - if self.context_data.has_key('dir'): + if 'dir' in self.context_data: output_folder = self.context_data.get('dir') - if self.context_data.has_key('dstdir'): + if 'dstdir' in self.context_data: output_folder = self.context_data.get('dstdir') else: # Disable dir option for generic pull command - if self.context_data.has_key('dir'): + if 'dir' in self.context_data: log.warn("dir option is disabled in pull command, please use --transdir, or specify value in zanata.xml") - if self.context_data.has_key('dstdir'): + if 'dstdir' in self.context_data: log.warn("dstdir option is changed to transdir option for generic pull command") output_folder = self.context_data.get('dstdir') - if self.context_data.has_key('noskeletons'): + if 'noskeletons' in self.context_data: skeletons = False outpath = self.create_outpath(output_folder) filedict = self.zanatacmd.get_project_translation_stats( self.project_id, self.version_id, self.context_data['mindocpercent'], lang_list, locale_map - ) if self.context_data.get('mindocpercent') else {file: lang_list for file in filelist} + ) if self.context_data.get('mindocpercent') else dict((file, lang_list) for file in filelist) self.zanatacmd.pull_command(locale_map, self.project_id, self.version_id, filedict, outpath, command_type, skeletons) diff --git a/zanataclient/pushcmd.py b/zanataclient/pushcmd.py index 3ec6d2a..c14548f 100644 --- a/zanataclient/pushcmd.py +++ b/zanataclient/pushcmd.py @@ -23,8 +23,8 @@ import os import sys -from cmdbase import PushPull -from zanatalib.logger import Logger +from .cmdbase import PushPull +from .zanatalib.logger import Logger log = Logger() @@ -40,14 +40,14 @@ def run(self): force = False project_type, deletefiles, tmlfolder, filelist = self.get_files() # Disable dir option for generic push command - if self.context_data.has_key('dir'): + if 'dir' in self.context_data: log.warn("dir option is disabled in push command, please use --srcdir and --transdir, or specify value in zanata.xml") - if self.context_data.has_key('pushtrans'): + if 'pushtrans' in self.context_data: log.warn("--push-trans is deprecated, please use '--push-type both' instead") pushtrans = True - if self.context_data.has_key('pushtype'): + if 'pushtype' in self.context_data: push_type = self.context_data.get('pushtype') if push_type == "source": pushtrans = False @@ -56,7 +56,7 @@ def run(self): elif push_type == "both": pushtrans = True - if self.context_data.has_key('pushtransonly'): + if 'pushtransonly' in self.context_data: push_trans_only = True if push_trans_only: @@ -71,7 +71,7 @@ def run(self): log.error("Can not find source folder, please specify the source folder with '--srcdir' or using zanata.xml") sys.exit(1) - if self.context_data.has_key('force'): + if 'force' in self.context_data: force = True if project_type == 'podir': @@ -107,7 +107,7 @@ def run(self): log.info("Reuse previous translation on server:%s" % self.copytrans) - if self.context_data.has_key('force'): + if 'force' in self.context_data: force = True log.info("POT directory (originals):%s" % tmlfolder) @@ -142,9 +142,9 @@ def run(self): else: log.info("Importing source documents only") - if self.context_data.has_key('force'): + if 'force' in self.context_data: force = True - if deletefiles == True: + if deletefiles is True: self.zanatacmd.del_server_content(tmlfolder, self.project_id, self.version_id, filelist, force, "gettext") if importpo: diff --git a/zanataclient/zanata.py b/zanataclient/zanata.py index feb43a6..ea8f0b3 100644 --- a/zanataclient/zanata.py +++ b/zanataclient/zanata.py @@ -28,21 +28,21 @@ import subprocess from functools import wraps -from zanatalib.logger import Logger -from context import ProjectContext -from cmdbase import ( +from .zanatalib.logger import Logger +from .context import ProjectContext +from .cmdbase import ( ListProjects, ProjectInfo, VersionInfo, CreateProject, CreateVersion, GlossaryPush, GlossaryDelete, Stats ) -from command import makeHandler -from command import strip_docstring -from command import parse_command_line -from command import handle_program -from pushcmd import PoPush -from pushcmd import PublicanPush -from pushcmd import GenericPush -from pullcmd import GenericPull -from initcmd import ZanataInit +from .command import makeHandler +from .command import strip_docstring +from .command import parse_command_line +from .command import handle_program +from .pushcmd import PoPush +from .pushcmd import PublicanPush +from .pushcmd import GenericPush +from .pullcmd import GenericPull +from .initcmd import ZanataInit log = Logger() @@ -348,26 +348,26 @@ def process_command(args): for arg in args[1:]: command = command + '_' + arg - if command_handler_factories.has_key(command): + if command in command_handler_factories: if hasattr(help, command): - print strip_docstring(getattr(help, command)) + print(strip_docstring(getattr(help, command))) else: fn = command_handler_factories[command]() - print strip_docstring((fn.__doc__ or 'No help')) + print(strip_docstring((fn.__doc__ or 'No help'))) sys.exit(0) else: if command == 'project': - print ("Command: 'zanata project info'\n" - " 'zanata project create'") + print("Command: 'zanata project info'\n" + " 'zanata project create'") elif command == 'version': - print ("Command: 'zanata version info'\n" - " 'zanata version create'") + print("Command: 'zanata version info'\n" + " 'zanata version create'") elif command == 'publican': - print ("Command: 'zanata publican push'\n" - " 'zanata publican pull'") + print("Command: 'zanata publican push'\n" + " 'zanata publican pull'") elif command == 'po': - print ("Command: 'zanata po push'\n" - " 'zanata po pull'") + print("Command: 'zanata po push'\n" + " 'zanata po pull'") else: log.error("No such command %r, Try 'zanata --help' for more information." % command.replace('_', ' ')) @@ -397,7 +397,7 @@ def help_info(command_options, args): if args: process_command(args) else: - print usage + print(usage) @command(ListProjects, False) @@ -734,7 +734,7 @@ def init(command_options, args): def signal_handler(signal, frame): - print '\nPressed Ctrl+C! Stop processing!' + print('\nPressed Ctrl+C! Stop processing!') sys.exit(0) @@ -755,13 +755,13 @@ def run(): args, program_name=os.path.split(sys.argv[0])[1], ) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: - print str(err) + print(str(err)) if command: - print "Try zanata %(command)s --help' for more information." % { + print("Try zanata %(command)s --help' for more information." % { 'command': command, - } + }) else: - print usage + print(usage) sys.exit(2) diff --git a/zanataclient/zanatacmd.py b/zanataclient/zanatacmd.py index 0805ce7..49daa7a 100644 --- a/zanataclient/zanatacmd.py +++ b/zanataclient/zanatacmd.py @@ -23,24 +23,25 @@ import sys import os -from publicanutil import PublicanUtility -from csvconverter import CSVConverter -from zanatalib.resource import ZanataResource -from zanatalib.glossaryservice import GlossaryService -from zanatalib.projectutils import ( +from .publicanutil import PublicanUtility +from .csvconverter import CSVConverter +from .zanatalib.resource import ZanataResource +from .zanatalib.projectutils import ( Project, Iteration, Stats ) -from zanatalib.logger import Logger -from zanatalib.error import ZanataException -from zanatalib.error import NoSuchProjectException -from zanatalib.error import UnAuthorizedException -from zanatalib.error import UnAvaliableResourceException -from zanatalib.error import BadRequestBodyException -from zanatalib.error import SameNameDocumentException -from zanatalib.error import InvalidOptionException -from zanatalib.error import UnexpectedStatusException -from zanatalib.error import UnavailableServiceError -from zanatalib.error import InternalServerError +from .zanatalib.logger import Logger +from .zanatalib.error import ( + ZanataException, NoSuchProjectException, UnAuthorizedException, + UnAvaliableResourceException, BadRequestBodyException, + SameNameDocumentException, InvalidOptionException, + UnexpectedStatusException, UnavailableServiceError, + InternalServerError +) + +try: + input = raw_input +except NameError: + pass class ZanataCommand: @@ -103,16 +104,16 @@ def check_project(self, command_options, project_config): def verify_project(self, project_id, version_id): try: self.zanata_resource.projects.get(project_id) - except NoSuchProjectException, e: + except NoSuchProjectException as e: self.log.error(str(e)) sys.exit(1) try: self.zanata_resource.projects.iterations.get(project_id, version_id) - except NoSuchProjectException, e: + except NoSuchProjectException as e: self.log.error(str(e)) sys.exit(1) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) def update_template(self, project_id, iteration_id, filename, body, copytrans): @@ -125,7 +126,7 @@ def update_template(self, project_id, iteration_id, filename, body, copytrans): result = self.zanata_resource.documents.update_template(project_id, iteration_id, request_name, body, copytrans) if result: self.log.info("Successfully updated template %s on the server" % filename) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) def commit_translation(self, project_id, iteration_id, request_name, pofile, lang, body, merge): @@ -134,14 +135,14 @@ def commit_translation(self, project_id, iteration_id, request_name, pofile, lan if result: self.log.warn(result) self.log.info("Successfully pushed translation %s to the Zanata server" % pofile) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) def del_server_content(self, tmlfolder, project_id, iteration_id, push_files, force, project_type): # Get the file list of this version of project try: filelist = self.zanata_resource.documents.get_file_list(project_id, iteration_id) - except Exception, e: + except Exception as e: self.log.error(str(e)) sys.exit(1) @@ -149,7 +150,7 @@ def del_server_content(self, tmlfolder, project_id, iteration_id, push_files, fo self.log.info("This will overwrite/delete any existing documents on the server.") if not force: while True: - option = raw_input("Are you sure (y/n)?") + option = input("Are you sure (y/n)?") if option.lower() == "yes" or option.lower() == "y": break elif option.lower() == "no" or option.lower() == "n": @@ -180,7 +181,7 @@ def del_server_content(self, tmlfolder, project_id, iteration_id, push_files, fo try: self.zanata_resource.documents.delete_template(project_id, iteration_id, request) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) sys.exit(1) @@ -200,11 +201,11 @@ def list_projects(self): sys.exit(1) for project in projects: - print ("\nProject ID: %s") % project.id - print ("Project Name: %s") % project.name + print("\nProject ID: %s") % project.id + print("Project Name: %s") % project.name if hasattr(project, 'defaultType') and project.defaultType.strip(): - print ("Project Type: %s") % project.defaultType - print ("Project Links: %s") % [{'href': link.href, 'type': link.type, 'rel': link.rel} for link in project.links] + print("Project Type: %s") % project.defaultType + print("Project Links: %s") % [{'href': link.href, 'type': link.type, 'rel': link.rel} for link in project.links] def project_info(self, project_id): """ @@ -212,14 +213,14 @@ def project_info(self, project_id): """ try: p = self.zanata_resource.projects.get(project_id) - print ("\nProject ID: %s") % p.id - print ("Project Name: %s") % p.name + print("\nProject ID: %s") % p.id + print("Project Name: %s") % p.name if hasattr(p, 'defaultType') and p.defaultType.strip(): - print ("Project Type: %s") % p.defaultType + print("Project Type: %s") % p.defaultType if hasattr(p, 'description') and p.description.strip(): - print ("Project Desc: %s") % p.description - print ("\n") - except NoSuchProjectException, e: + print("Project Desc: %s") % p.description + print("\n") + except NoSuchProjectException as e: self.log.error(str(e)) except InvalidOptionException: self.log.error("Options are not valid") @@ -232,7 +233,7 @@ def get_project_versions(self, project_id): for iteration in p.iterations: project_versions.append(iteration.get('id')) return project_versions - except NoSuchProjectException, e: + except NoSuchProjectException as e: self.log.error(str(e)) except InvalidOptionException: self.log.error("Options are not valid") @@ -244,12 +245,12 @@ def version_info(self, project_id, iteration_id): try: project = self.zanata_resource.projects.get(project_id) iteration = project.get_iteration(iteration_id) - print ("Version ID: %s") % iteration.id + print("Version ID: %s") % iteration.id if hasattr(iteration, 'name'): - print ("Version Name: %s") % iteration.name + print("Version Name: %s") % iteration.name if hasattr(iteration, 'description'): - print ("Version Description: %s") % iteration.description - except NoSuchProjectException, e: + print("Version Description: %s") % iteration.description + except NoSuchProjectException as e: self.log.error(str(e)) def create_project(self, project_id, project_name, project_desc, project_type): @@ -265,7 +266,7 @@ def create_project(self, project_id, project_name, project_desc, project_type): if result: self.log.info("Successfully created project: %s" % project_id) return True - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) def create_version(self, project_id, version_id, version_name=None, version_desc=None): @@ -280,7 +281,7 @@ def create_version(self, project_id, version_id, version_name=None, version_desc if result: self.log.info("Successfully created version: %s" % version_id) return True - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) def import_po(self, potfile, trans_folder, project_id, iteration_id, lang_list, locale_map, merge, project_type): @@ -339,7 +340,7 @@ def push_trans_command(self, transfolder, project_id, iteration_id, lang_list, l try: filelist = self.zanata_resource.documents.get_file_list(project_id, iteration_id) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) if not filelist: @@ -377,7 +378,7 @@ def push_trans_command(self, transfolder, project_id, iteration_id, lang_list, l pofile = filepath[0:filepath.rfind('/') + 1] + pofile_name except: pofile = None - print "Can not find " + name + print("Can not find " + name) elif project_type == "podir": if '/' in filename: @@ -420,16 +421,16 @@ def push_command(self, file_list, srcfolder, project_id, iteration_id, copytrans result = self.update_template(project_id, iteration_id, filename, body, copytrans) if result: self.log.info("Successfully pushed %s to the server" % filepath) - except UnAuthorizedException, e: + except UnAuthorizedException as e: self.log.error(str(e)) break - except BadRequestBodyException, e: + except BadRequestBodyException as e: self.log.error(str(e)) continue - except UnexpectedStatusException, e: + except UnexpectedStatusException as e: self.log.error(str(e)) continue - except InternalServerError, e: + except InternalServerError as e: self.log.error(str(e)) sys.exit(1) @@ -468,16 +469,16 @@ def pull_command(self, locale_map, project_id, iteration_id, filedict, output, p try: pot = self.zanata_resource.documents.retrieve_template(project_id, iteration_id, request_name) - except UnAuthorizedException, e: + except UnAuthorizedException as e: self.log.error(str(e)) break - except UnAvaliableResourceException, e: + except UnAvaliableResourceException as e: self.log.error("Can't find pot file for %s on server" % name) break - except UnexpectedStatusException, e: + except UnexpectedStatusException as e: self.log.error(str(e)) break - except InternalServerError, e: + except InternalServerError as e: self.log.error(str(e)) sys.exit(1) @@ -512,17 +513,17 @@ def pull_command(self, locale_map, project_id, iteration_id, filedict, output, p try: result = self.zanata_resource.documents.retrieve_translation(lang, project_id, iteration_id, request_name, skeletons) publicanutil.save_to_pofile(pofile, result, pot, skeletons, item, name) - except UnAuthorizedException, e: + except UnAuthorizedException as e: self.log.error(str(e)) break - except UnAvaliableResourceException, e: + except UnAvaliableResourceException as e: self.log.info("There is no %s translation for %s" % (item, name)) - except BadRequestBodyException, e: + except BadRequestBodyException as e: self.log.error(str(e)) continue - except UnexpectedStatusException, e: + except UnexpectedStatusException as e: self.log.error(str(e)) - except InternalServerError, e: + except InternalServerError as e: self.log.error(str(e)) sys.exit(1) @@ -540,7 +541,7 @@ def poglossary_push(self, path, lang, sourcecomments): self.log.info("Push part %s of glossary file" % i) try: self.zanata_resource.glossary.commit_glossary(jsons[i]) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) sys.exit(1) i += 1 @@ -554,13 +555,13 @@ def csvglossary_push(self, path, locale_map, comments_header): content = self.zanata_resource.glossary.commit_glossary(json) if content: self.log.info("Successfully pushed glossary to the server") - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) def delete_glossary(self, lang=None): try: self.zanata_resource.glossary.delete(lang) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) else: self.log.info("Successfully delete the glossary terms on the server") @@ -569,7 +570,7 @@ def get_project_translation_stats(self, project_id, project_version, min_doc_per doc_locales_dict = {} try: server_return = self.zanata_resource.stats.get_project_stats(project_id, project_version) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) else: percent_dict = Stats(server_return).trans_percent_dict @@ -590,7 +591,7 @@ def get_project_translation_stats(self, project_id, project_version, min_doc_per return doc_locales_dict def _print_double_line(self, length): - print '=' * length + print('=' * length) def _print_new_line_row(self, sequence, header=None): pattern = ( @@ -598,7 +599,7 @@ def _print_new_line_row(self, sequence, header=None): if header else " %-10s %-8s %-4s %5s %10s %14s %32s" ) - print pattern % sequence + print(pattern % sequence) def _display_stats(self, collection, locale_map): self._print_double_line(90) @@ -619,7 +620,7 @@ def _display_stats(self, collection, locale_map): print('\n') def _display_doc_stats(self, doc_name, stats_dict, locale_map): - print ('Document: %s' % doc_name) + print('Document: %s' % doc_name) self._display_stats(stats_dict, locale_map) def display_translation_stats(self, *args, **kwargs): @@ -632,7 +633,7 @@ def display_translation_stats(self, *args, **kwargs): project_id, project_version, kwargs['docid'], 'wordstats' in kwargs, kwargs.get('lang') ) - except ZanataException, e: + except ZanataException as e: self.log.error(str(e)) else: trans_stats = Stats(server_return) diff --git a/zanataclient/zanatalib/__init__.py b/zanataclient/zanatalib/__init__.py index d3db984..2ee3666 100644 --- a/zanataclient/zanatalib/__init__.py +++ b/zanataclient/zanatalib/__init__.py @@ -20,10 +20,10 @@ # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. -from resource import * -from docservice import * -from error import * -from projectservice import * -from projectutils import * -from versionservice import * -from logger import * +from .resource import * +from .docservice import * +from .error import * +from .projectservice import * +from .projectutils import * +from .versionservice import * +from .logger import * diff --git a/zanataclient/zanatalib/docservice.py b/zanataclient/zanatalib/docservice.py index 03228cc..eddd672 100644 --- a/zanataclient/zanatalib/docservice.py +++ b/zanataclient/zanatalib/docservice.py @@ -25,7 +25,7 @@ "DocumentService", ) -from service import Service +from .service import Service class DocumentService(Service): diff --git a/zanataclient/zanatalib/glossaryservice.py b/zanataclient/zanatalib/glossaryservice.py index 6a5c347..650f97d 100644 --- a/zanataclient/zanatalib/glossaryservice.py +++ b/zanataclient/zanatalib/glossaryservice.py @@ -26,7 +26,7 @@ ) -from service import Service +from .service import Service class GlossaryService(Service): diff --git a/zanataclient/zanatalib/logger.py b/zanataclient/zanatalib/logger.py index a4bc72b..3bd85e3 100644 --- a/zanataclient/zanatalib/logger.py +++ b/zanataclient/zanatalib/logger.py @@ -46,18 +46,18 @@ def __init__(self): def info(self, message): if self.enable_infoprefix: - print self.info_prefix + message + print(self.info_prefix + message) else: - print message + print(message) def warn(self, message): if self.enable_warnprefix: - print self.warn_prefix + message + print(self.warn_prefix + message) else: - print message + print(message) def error(self, message): if self.enable_errprefix: - print self.error_prefix + message + print(self.error_prefix + message) else: - print message + print(message) diff --git a/zanataclient/zanatalib/projectservice.py b/zanataclient/zanatalib/projectservice.py index c279497..bf14b8f 100644 --- a/zanataclient/zanatalib/projectservice.py +++ b/zanataclient/zanatalib/projectservice.py @@ -25,9 +25,9 @@ ) -from projectutils import Project -from projectutils import Iteration -from service import Service +from .projectutils import Project +from .projectutils import Iteration +from .service import Service class ProjectService(Service): @@ -67,9 +67,9 @@ def get(self, projectid): res, content = self.restclient.process_request('list_project', projectid, headers=self.http_headers) server_return = self.messages(res, content) - if server_return.has_key('status'): + if 'status' in server_return: if server_return['status'] == "Retired": - print "Warning: The project %s is retired!" % projectid + print("Warning: The project %s is retired!" % projectid) project = Project(server_return) project.set_iteration(self.iterations) return project @@ -122,9 +122,9 @@ def get(self, projectid, iterationid): res, content = self.restclient.process_request('get_iteration', projectid, iterationid, headers=self.http_headers) server_return = self.messages(res, content) - if server_return.has_key('status'): + if 'status' in server_return: if server_return['status'] == "Retired": - print "Warning: The project %s is retired!" % iterationid + print("Warning: The project %s is retired!" % iterationid) return Iteration(server_return) def create(self, projectid, iteration): diff --git a/zanataclient/zanatalib/projectutils.py b/zanataclient/zanatalib/projectutils.py index cacec01..d8b5dfe 100644 --- a/zanataclient/zanatalib/projectutils.py +++ b/zanataclient/zanatalib/projectutils.py @@ -25,6 +25,7 @@ "Project", "Iteration", "Stats" ) +import sys from xml.dom import minidom import xml.etree.cElementTree as ET @@ -67,7 +68,7 @@ def _get_doc_trans_percent(self, doc_name, stats_dict): for stat in stats_dict: if stat.get('locale'): trans_percent.update({ - stat['locale']: int((float(stat.get('translated', 0) * 100) / + stat['locale']: int((float(stat.get('translated', 0) * 100) // float(stat.get('total', 0)))) }) return {doc_name: trans_percent} @@ -132,8 +133,9 @@ def dict2xml(tag, dict): ''' Converts dict of key/value pairs into XML ''' - xml_ns = "http://zanata.org/namespace/config/" - ET.register_namespace('', xml_ns) + if sys.version_info >= (2, 7): + xml_ns = "http://zanata.org/namespace/config/" + ET.register_namespace('', xml_ns) elem = ET.Element(tag) for key, val in dict.items(): child = ET.Element(key) diff --git a/zanataclient/zanatalib/resource.py b/zanataclient/zanatalib/resource.py index a38cc45..a7014ed 100644 --- a/zanataclient/zanatalib/resource.py +++ b/zanataclient/zanatalib/resource.py @@ -25,11 +25,11 @@ "ZanataResource", ) -from docservice import DocumentService -from projectservice import ProjectService -from versionservice import VersionService -from glossaryservice import GlossaryService -from statservice import StatService +from .docservice import DocumentService +from .projectservice import ProjectService +from .versionservice import VersionService +from .glossaryservice import GlossaryService +from .statservice import StatService class ZanataResource: diff --git a/zanataclient/zanatalib/rest/__init__.py b/zanataclient/zanatalib/rest/__init__.py index 8fa1e46..630927e 100644 --- a/zanataclient/zanatalib/rest/__init__.py +++ b/zanataclient/zanatalib/rest/__init__.py @@ -20,4 +20,4 @@ # Boston, MA 02110-1301, USA. -from client import RestClient +from .client import RestClient diff --git a/zanataclient/zanatalib/rest/client.py b/zanataclient/zanatalib/rest/client.py index 8a66639..bb29226 100644 --- a/zanataclient/zanatalib/rest/client.py +++ b/zanataclient/zanatalib/rest/client.py @@ -23,20 +23,23 @@ "RestClient", ) -import urlparse +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse import sys import warnings -import StringIO +from io import StringIO warnings.simplefilter("ignore", DeprecationWarning) import httplib2 -from config import http_methods, ServiceConfig +from .config import ServiceConfig class RestClient(object): def __init__(self, base_url, disable_ssl_certificate_validation=True): self.base_url = base_url - self.url = urlparse.urlparse(base_url) + self.url = urlparse(base_url) self.http_client = httplib2.Http(disable_ssl_certificate_validation=True) def disable_ssl_cert_validation(self): @@ -51,7 +54,7 @@ def request(self, resource, method="get", body=None, headers=None, extension=Non if body is not None: thelen = str(len(body)) headers['Content-Length'] = thelen - body = StringIO.StringIO(body) + body = StringIO(body) try: response, content = self.http_client.request(resource, method.upper(), body, headers=headers) @@ -62,27 +65,28 @@ def request(self, resource, method="get", body=None, headers=None, extension=Non elif 'location' in response.previous: new_url = response.previous['location'] if new_url: - print "\nRedirecting to: %s" % '{uri.scheme}://{uri.netloc}/'.format(uri=urlparse.urlparse(new_url)) - print "HTTP Redirect: Please update the Server URL." + print("\nRedirecting to: %s" % '{uri.scheme}://{uri.netloc}/'.format(uri=urlparse(new_url))) + print("HTTP Redirect: Please update the Server URL.") response, content = self.http_client.request(new_url, method.upper(), body, headers=headers) return (response, content.decode("UTF-8")) - except httplib2.ServerNotFoundError, e: - print "error: %s, Maybe the Zanata server is down?" % e + except httplib2.ServerNotFoundError as e: + print("error: %s, Maybe the Zanata server is down?" % e) sys.exit(2) - except httplib2.HttpLib2Error, e: - print "error: %s" % e + except httplib2.HttpLib2Error as e: + print("error: %s" % e) sys.exit(2) - except MemoryError, e: - print "error: The file is too big to process" - except Exception, e: + except MemoryError as e: + print("error: The file is too big to process") + except Exception as e: value = str(e).rstrip() if value == 'a float is required': - print "error: Error happens when processing https" + print("error: Error happens when processing https") if sys.version_info[:2] == (2, 6): - print "If version of python-httplib2 < 0.4.0, please use the patch in http://code.google.com/p/httplib2/issues/detail?id=39" + print("If version of python-httplib2 < 0.4.0, " + "please use the patch in http://code.google.com/p/httplib2/issues/detail?id=39") sys.exit(2) else: - print "error: %s" % e + print("error: %s" % e) sys.exit(2) def process_request(self, service_name, *args, **kwargs): diff --git a/zanataclient/zanatalib/rest/config.py b/zanataclient/zanatalib/rest/config.py index c3b320c..0c4ce27 100644 --- a/zanataclient/zanatalib/rest/config.py +++ b/zanataclient/zanatalib/rest/config.py @@ -19,9 +19,13 @@ # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. -from collections import ( - namedtuple, OrderedDict -) +from collections import namedtuple + +try: + from collections import OrderedDict +except ImportError: + from ordereddict import OrderedDict + middle_url = '/seam/resource/restv1' http_methods = ('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH', 'OPTIONS') @@ -195,32 +199,32 @@ resource = namedtuple('service', 'rest_resource mount_point http_method') # service-to-resource mappings -server_version = resource('VersionResource', resource_config_dict['VersionResource'].keys()[0], http_methods[0]) -list_projects = resource('ProjectsResource', resource_config_dict['ProjectsResource'].keys()[0], http_methods[0]) -list_project = resource('ProjectResource', resource_config_dict['ProjectResource'].keys()[0], http_methods[0]) -create_project = resource('ProjectResource', resource_config_dict['ProjectResource'].keys()[0], http_methods[2]) -get_iteration = resource('ProjectIterationResource', resource_config_dict['ProjectIterationResource'].keys()[0], +server_version = resource('VersionResource', list(resource_config_dict['VersionResource'].keys())[0], http_methods[0]) +list_projects = resource('ProjectsResource', list(resource_config_dict['ProjectsResource'].keys())[0], http_methods[0]) +list_project = resource('ProjectResource', list(resource_config_dict['ProjectResource'].keys())[0], http_methods[0]) +create_project = resource('ProjectResource', list(resource_config_dict['ProjectResource'].keys())[0], http_methods[2]) +get_iteration = resource('ProjectIterationResource', list(resource_config_dict['ProjectIterationResource'].keys())[0], http_methods[0]) -create_iteration = resource('ProjectIterationResource', resource_config_dict['ProjectIterationResource'].keys()[0], +create_iteration = resource('ProjectIterationResource', list(resource_config_dict['ProjectIterationResource'].keys())[0], http_methods[2]) -commit_glossary = resource('GlossaryResource', resource_config_dict['GlossaryResource'].keys()[0], http_methods[2]) -delete_glossary = resource('GlossaryResource', resource_config_dict['GlossaryResource'].keys()[0], http_methods[3]) -list_files = resource('SourceDocResource', resource_config_dict['SourceDocResource'].keys()[0], http_methods[0]) -commit_template = resource('SourceDocResource', resource_config_dict['SourceDocResource'].keys()[0], http_methods[1]) -retrieve_template = resource('SourceDocResource', resource_config_dict['SourceDocResource'].keys()[1], http_methods[0]) -update_template = resource('SourceDocResource', resource_config_dict['SourceDocResource'].keys()[1], http_methods[2]) -delete_template = resource('SourceDocResource', resource_config_dict['SourceDocResource'].keys()[1], http_methods[3]) -retrieve_translation = resource('TranslatedDocResource', resource_config_dict['TranslatedDocResource'].keys()[0], +commit_glossary = resource('GlossaryResource', list(resource_config_dict['GlossaryResource'].keys())[0], http_methods[2]) +delete_glossary = resource('GlossaryResource', list(resource_config_dict['GlossaryResource'].keys())[0], http_methods[3]) +list_files = resource('SourceDocResource', list(resource_config_dict['SourceDocResource'].keys())[0], http_methods[0]) +commit_template = resource('SourceDocResource', list(resource_config_dict['SourceDocResource'].keys())[0], http_methods[1]) +retrieve_template = resource('SourceDocResource', list(resource_config_dict['SourceDocResource'].keys())[1], http_methods[0]) +update_template = resource('SourceDocResource', list(resource_config_dict['SourceDocResource'].keys())[1], http_methods[2]) +delete_template = resource('SourceDocResource', list(resource_config_dict['SourceDocResource'].keys())[1], http_methods[3]) +retrieve_translation = resource('TranslatedDocResource', list(resource_config_dict['TranslatedDocResource'].keys())[0], http_methods[0]) -commit_translation = resource('TranslatedDocResource', resource_config_dict['TranslatedDocResource'].keys()[0], +commit_translation = resource('TranslatedDocResource', list(resource_config_dict['TranslatedDocResource'].keys())[0], http_methods[2]) -project_locales = resource('ProjectLocalesResource', resource_config_dict['ProjectLocalesResource'].keys()[0], +project_locales = resource('ProjectLocalesResource', list(resource_config_dict['ProjectLocalesResource'].keys())[0], http_methods[0]) iteration_locales = resource('ProjectIterationLocalesResource', - resource_config_dict['ProjectIterationLocalesResource'].keys()[0], http_methods[0]) -proj_trans_stats = resource('StatisticsResource', resource_config_dict['StatisticsResource'].keys()[0], http_methods[0]) -doc_trans_stats = resource('StatisticsResource', resource_config_dict['StatisticsResource'].keys()[1], http_methods[0]) -project_config = resource('ProjectIterationResource', resource_config_dict['ProjectIterationResource'].keys()[1], + list(resource_config_dict['ProjectIterationLocalesResource'].keys())[0], http_methods[0]) +proj_trans_stats = resource('StatisticsResource', list(resource_config_dict['StatisticsResource'].keys())[0], http_methods[0]) +doc_trans_stats = resource('StatisticsResource', list(resource_config_dict['StatisticsResource'].keys())[1], http_methods[0]) +project_config = resource('ProjectIterationResource', list(resource_config_dict['ProjectIterationResource'].keys())[1], http_methods[0]) # zanata-python-client operates on services listed here zpc_services = { @@ -265,7 +269,7 @@ def resource_group(self): @property def mount_points(self): - return self._config_dict[self._service.rest_resource].keys() + return list(self._config_dict[self._service.rest_resource].keys()) @property def resource(self): diff --git a/zanataclient/zanatalib/statservice.py b/zanataclient/zanatalib/statservice.py index 55335f8..e6de5bf 100644 --- a/zanataclient/zanatalib/statservice.py +++ b/zanataclient/zanatalib/statservice.py @@ -25,7 +25,7 @@ "StatService", ) -from service import Service +from .service import Service class StatService(Service): diff --git a/zanataclient/zanatalib/versionservice.py b/zanataclient/zanatalib/versionservice.py index 61b2be7..ccded8e 100644 --- a/zanataclient/zanatalib/versionservice.py +++ b/zanataclient/zanatalib/versionservice.py @@ -25,7 +25,7 @@ "VersionService", ) -from service import Service +from .service import Service class VersionService(Service): From 5bd43dcc9db7ed60d07114ca9e1386877945b290 Mon Sep 17 00:00:00 2001 From: Sundeep Anand Date: Wed, 20 Jan 2016 20:24:51 +0530 Subject: [PATCH 3/3] python2.6 support --- .travis.yml | 2 -- CHANGELOG | 3 +++ setup.py | 2 ++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1774785..c8bdbe9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,5 @@ language: python python: - - "2.4" - - "2.5" - "2.6" - "2.7" # command to install dependencies diff --git a/CHANGELOG b/CHANGELOG index 0ccfc3c..5441f5c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,6 @@ +* Wed Jan 20 2016 Sundeep Anand - 1.4.2 +- Python 2.6 Support + * Tue Jan 12 2016 Sundeep Anand - 1.4.1 - Implemented zanata init (ZNTA-780) - Bug ZNTA-853 - Crash when pushing local translations diff --git a/setup.py b/setup.py index 556f04a..d62d78f 100755 --- a/setup.py +++ b/setup.py @@ -83,5 +83,7 @@ def get_client_version(): 'License :: OSI Approved :: GNU Lesser General Public License (LGPL)', 'Operating System :: Unix', 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', ], )