changeset 7844:a8e6bb9ee9ea

future: use Python print function
author Mads Kiilerich <mads@kiilerich.com>
date Sun, 18 Aug 2019 20:25:18 +0200
parents e2e5140704fc
children 3b54bcf6d128 12f36f3afc56
files kallithea/bin/kallithea_api.py kallithea/bin/kallithea_cli_ishell.py kallithea/bin/kallithea_gist.py kallithea/bin/ldap_sync.py kallithea/lib/db_manage.py kallithea/lib/pidlock.py kallithea/lib/utils2.py kallithea/lib/vcs/utils/progressbar.py kallithea/tests/other/test_vcs_operations.py kallithea/tests/scripts/manual_test_concurrency.py kallithea/tests/scripts/manual_test_crawler.py scripts/docs-headings.py scripts/generate-ini.py scripts/logformat.py
diffstat 14 files changed, 112 insertions(+), 84 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/bin/kallithea_api.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/bin/kallithea_api.py	Sun Aug 18 20:25:18 2019 +0200
@@ -25,6 +25,8 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
+from __future__ import print_function
+
 import argparse
 import sys
 
@@ -104,7 +106,7 @@
         sys.stderr.write('Error parsing arguments \n')
         sys.exit()
     if args.format == FORMAT_PRETTY:
-        print 'Calling method %s => %s' % (method, apihost)
+        print('Calling method %s => %s' % (method, apihost))
 
     json_resp = api_call(apikey, apihost, method, **margs)
     error_prefix = ''
@@ -114,11 +116,11 @@
     else:
         json_data = json_resp['result']
     if args.format == FORMAT_JSON:
-        print json.dumps(json_data)
+        print(json.dumps(json_data))
     elif args.format == FORMAT_PRETTY:
-        print 'Server response \n%s%s' % (
+        print('Server response \n%s%s' % (
             error_prefix, json.dumps(json_data, indent=4, sort_keys=True)
-        )
+        ))
     return 0
 
 
--- a/kallithea/bin/kallithea_cli_ishell.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/bin/kallithea_cli_ishell.py	Sun Aug 18 20:25:18 2019 +0200
@@ -19,6 +19,9 @@
 :copyright: (c) 2013 RhodeCode GmbH, and others.
 :license: GPLv3, see LICENSE.md for more details.
 """
+
+from __future__ import print_function
+
 import sys
 
 import kallithea.bin.kallithea_cli_base as cli_base
@@ -31,7 +34,7 @@
     try:
         from IPython import embed
     except ImportError:
-        print 'Kallithea ishell requires the Python package IPython 4 or later'
+        print('Kallithea ishell requires the Python package IPython 4 or later')
         sys.exit(-1)
     from traitlets.config.loader import Config
     cfg = Config()
--- a/kallithea/bin/kallithea_gist.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/bin/kallithea_gist.py	Sun Aug 18 20:25:18 2019 +0200
@@ -25,6 +25,8 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
+from __future__ import print_function
+
 import argparse
 import fileinput
 import os
@@ -144,11 +146,11 @@
 
         json_data = api_call(apikey, host, 'create_gist', **margs)['result']
         if args.format == FORMAT_JSON:
-            print json.dumps(json_data)
+            print(json.dumps(json_data))
         elif args.format == FORMAT_PRETTY:
-            print json_data
-            print 'Created %s gist %s' % (json_data['gist']['type'],
-                                          json_data['gist']['url'])
+            print(json_data)
+            print('Created %s gist %s' % (json_data['gist']['type'],
+                                          json_data['gist']['url']))
     return 0
 
 
@@ -164,7 +166,7 @@
     try:
         return _run(argv)
     except Exception as e:
-        print e
+        print(e)
         return 1
 
 
--- a/kallithea/bin/ldap_sync.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/bin/ldap_sync.py	Sun Aug 18 20:25:18 2019 +0200
@@ -25,6 +25,8 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
+from __future__ import print_function
+
 import urllib2
 import uuid
 from ConfigParser import ConfigParser
@@ -242,7 +244,7 @@
 
 if __name__ == '__main__':
     sync = LdapSync()
-    print sync.update_groups_from_ldap()
+    print(sync.update_groups_from_ldap())
 
     for gr in sync.ldap_client.get_groups():
         # TODO: exception when user does not exist during add membership...
--- a/kallithea/lib/db_manage.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/lib/db_manage.py	Sun Aug 18 20:25:18 2019 +0200
@@ -26,6 +26,8 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
+from __future__ import print_function
+
 import logging
 import os
 import sys
@@ -86,7 +88,7 @@
         else:
             destroy = self._ask_ok('Are you sure to destroy old database ? [y/n]')
         if not destroy:
-            print 'Nothing done.'
+            print('Nothing done.')
             sys.exit(0)
         if destroy:
             # drop and re-create old schemas
--- a/kallithea/lib/pidlock.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/lib/pidlock.py	Sun Aug 18 20:25:18 2019 +0200
@@ -12,6 +12,8 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import errno
 import os
 from multiprocessing.util import Finalize
@@ -50,7 +52,7 @@
     def _on_finalize(lock, debug):
         if lock.held:
             if debug:
-                print 'lock held finalizing and running lock.release()'
+                print('lock held finalizing and running lock.release()')
             lock.release()
 
     def lock(self):
@@ -60,7 +62,7 @@
         """
         lockname = str(os.getpid())
         if self.debug:
-            print 'running lock'
+            print('running lock')
         self.trylock()
         self.makelock(lockname, self.pidfile)
         return True
@@ -68,7 +70,7 @@
     def trylock(self):
         running_pid = False
         if self.debug:
-            print 'checking for already running process'
+            print('checking for already running process')
         try:
             with open(self.pidfile, 'r') as f:
                 try:
@@ -77,8 +79,8 @@
                     running_pid = -1
 
             if self.debug:
-                print ('lock file present running_pid: %s, '
-                       'checking for execution' % (running_pid,))
+                print('lock file present running_pid: %s, '
+                      'checking for execution' % (running_pid,))
             # Now we check the PID from lock file matches to the current
             # process PID
             if running_pid:
@@ -88,13 +90,13 @@
                     if exc.errno in (errno.ESRCH, errno.EPERM):
                         print ("Lock File is there but"
                                " the program is not running")
-                        print "Removing lock file for the: %s" % running_pid
+                        print("Removing lock file for the: %s" % running_pid)
                         self.release()
                     else:
                         raise
                 else:
-                    print "You already have an instance of the program running"
-                    print "It is running as process %s" % running_pid
+                    print("You already have an instance of the program running")
+                    print("It is running as process %s" % running_pid)
                     raise LockHeld()
 
         except IOError as e:
@@ -105,21 +107,21 @@
         """releases the pid by removing the pidfile
         """
         if self.debug:
-            print 'trying to release the pidlock'
+            print('trying to release the pidlock')
 
         if self.callbackfn:
             #execute callback function on release
             if self.debug:
-                print 'executing callback function %s' % self.callbackfn
+                print('executing callback function %s' % self.callbackfn)
             self.callbackfn()
         try:
             if self.debug:
-                print 'removing pidfile %s' % self.pidfile
+                print('removing pidfile %s' % self.pidfile)
             os.remove(self.pidfile)
             self.held = False
         except OSError as e:
             if self.debug:
-                print 'removing pidfile failed %s' % e
+                print('removing pidfile failed %s' % e)
             pass
 
     def makelock(self, lockname, pidfile):
@@ -130,7 +132,7 @@
         :param pidfile: the file to write the pid in
         """
         if self.debug:
-            print 'creating a file %s and pid: %s' % (pidfile, lockname)
+            print('creating a file %s and pid: %s' % (pidfile, lockname))
 
         dir_, file_ = os.path.split(pidfile)
         if not os.path.isdir(dir_):
--- a/kallithea/lib/utils2.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/lib/utils2.py	Sun Aug 18 20:25:18 2019 +0200
@@ -27,6 +27,7 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
+from __future__ import print_function
 
 import binascii
 import datetime
@@ -697,4 +698,4 @@
         retries = retries - 1
         if retries < 0:
             raise IOError
-        print complaint
+        print(complaint)
--- a/kallithea/lib/vcs/utils/progressbar.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/lib/vcs/utils/progressbar.py	Sun Aug 18 20:25:18 2019 +0200
@@ -1,4 +1,7 @@
 # encoding: UTF-8
+
+from __future__ import print_function
+
 import datetime
 import string
 import sys
@@ -354,54 +357,54 @@
 def main():
     import time
 
-    print "Standard progress bar..."
+    print("Standard progress bar...")
     bar = ProgressBar(30)
     for x in xrange(1, 31):
         bar.render(x)
         time.sleep(0.02)
     bar.stream.write('\n')
-    print
+    print()
 
-    print "Empty bar..."
+    print("Empty bar...")
     bar = ProgressBar(50)
     bar.render(0)
-    print
-    print
+    print()
+    print()
 
-    print "Colored bar..."
+    print("Colored bar...")
     bar = ColoredProgressBar(20)
     for x in bar:
         time.sleep(0.01)
-    print
+    print()
 
-    print "Animated char bar..."
+    print("Animated char bar...")
     bar = AnimatedProgressBar(20)
     for x in bar:
         time.sleep(0.01)
-    print
+    print()
 
-    print "Animated + colored char bar..."
+    print("Animated + colored char bar...")
     bar = AnimatedColoredProgressBar(20)
     for x in bar:
         time.sleep(0.01)
-    print
+    print()
 
-    print "Bar only ..."
+    print("Bar only ...")
     bar = BarOnlyProgressBar(20)
     for x in bar:
         time.sleep(0.01)
-    print
+    print()
 
-    print "Colored, longer bar-only, eta, total time ..."
+    print("Colored, longer bar-only, eta, total time ...")
     bar = BarOnlyColoredProgressBar(40)
     bar.width = 60
     bar.elements += ['time', 'eta']
     for x in bar:
         time.sleep(0.01)
-    print
-    print
+    print()
+    print()
 
-    print "File transfer bar, breaks after 2 seconds ..."
+    print("File transfer bar, breaks after 2 seconds ...")
     total_bytes = 1024 * 1024 * 2
     bar = ProgressBar(total_bytes)
     bar.width = 50
@@ -413,8 +416,8 @@
         now = datetime.datetime.now()
         if now - bar.started >= datetime.timedelta(seconds=2):
             break
-    print
-    print
+    print()
+    print()
 
 
 if __name__ == '__main__':
--- a/kallithea/tests/other/test_vcs_operations.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/tests/other/test_vcs_operations.py	Sun Aug 18 20:25:18 2019 +0200
@@ -25,6 +25,8 @@
 
 """
 
+from __future__ import print_function
+
 import json
 import os
 import re
@@ -144,7 +146,7 @@
         command = ' '.join(args)
         ignoreReturnCode = environ.pop('ignoreReturnCode', False)
         if DEBUG:
-            print '*** CMD %s ***' % command
+            print('*** CMD %s ***' % command)
         testenv = dict(os.environ)
         testenv['LANG'] = 'en_US.UTF-8'
         testenv['LANGUAGE'] = 'en_US:en'
@@ -155,9 +157,9 @@
         stdout, stderr = p.communicate()
         if DEBUG:
             if stdout:
-                print 'stdout:', stdout
+                print('stdout:', stdout)
             if stderr:
-                print 'stderr:', stderr
+                print('stderr:', stderr)
         if not ignoreReturnCode:
             assert p.returncode == 0
         return stdout, stderr
--- a/kallithea/tests/scripts/manual_test_concurrency.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/tests/scripts/manual_test_concurrency.py	Sun Aug 18 20:25:18 2019 +0200
@@ -26,6 +26,8 @@
 
 """
 
+from __future__ import print_function
+
 import logging
 import os
 import shutil
@@ -72,11 +74,11 @@
         command = cmd + ' ' + ' '.join(args)
         log.debug('Executing %s', command)
         if DEBUG:
-            print command
+            print(command)
         p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd)
         stdout, stderr = p.communicate()
         if DEBUG:
-            print stdout, stderr
+            print(stdout, stderr)
         return stdout, stderr
 
 
@@ -88,20 +90,20 @@
 
 
 def create_test_user(force=True):
-    print 'creating test user'
+    print('creating test user')
     sa = get_session()
 
     user = sa.query(User).filter(User.username == USER).scalar()
 
     if force and user is not None:
-        print 'removing current user'
+        print('removing current user')
         for repo in sa.query(Repository).filter(Repository.user == user).all():
             sa.delete(repo)
         sa.delete(user)
         sa.commit()
 
     if user is None or force:
-        print 'creating new one'
+        print('creating new one')
         new_usr = User()
         new_usr.username = USER
         new_usr.password = get_crypt_password(PASS)
@@ -113,11 +115,11 @@
         sa.add(new_usr)
         sa.commit()
 
-    print 'done'
+    print('done')
 
 
 def create_test_repo(force=True):
-    print 'creating test repo'
+    print('creating test repo')
     from kallithea.model.repo import RepoModel
     sa = get_session()
 
@@ -128,7 +130,7 @@
     repo = sa.query(Repository).filter(Repository.repo_name == HG_REPO).scalar()
 
     if repo is None:
-        print 'repo not found creating'
+        print('repo not found creating')
 
         form_data = {'repo_name': HG_REPO,
                      'repo_type': 'hg',
@@ -138,7 +140,7 @@
         rm.base_path = '/home/hg'
         rm.create(form_data, user)
 
-    print 'done'
+    print('done')
 
 
 def set_anonymous_access(enable=True):
@@ -208,9 +210,9 @@
                                         backend=backend)
         s = time.time()
         for i in range(1, int(sys.argv[2]) + 1):
-            print 'take', i
+            print('take', i)
             test_clone_with_credentials(repo=sys.argv[1], method=METHOD,
                                         backend=backend)
-        print 'time taken %.3f' % (time.time() - s)
+        print('time taken %.3f' % (time.time() - s))
     except Exception as e:
         sys.exit('stop on %s' % e)
--- a/kallithea/tests/scripts/manual_test_crawler.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/kallithea/tests/scripts/manual_test_crawler.py	Sun Aug 18 20:25:18 2019 +0200
@@ -30,6 +30,7 @@
 :license: GPLv3, see LICENSE.md for more details.
 """
 
+from __future__ import print_function
 
 import cookielib
 import os
@@ -61,7 +62,7 @@
 if not BASE_URI.endswith('/'):
     BASE_URI += '/'
 
-print 'Crawling @ %s' % BASE_URI
+print('Crawling @ %s' % BASE_URI)
 BASE_URI += '%s'
 PROJECT_PATH = os.path.join('/', 'home', 'username', 'repos')
 PROJECTS = [
@@ -109,16 +110,16 @@
         size = len(f.read())
         e = time.time() - s
         total_time += e
-        print 'visited %s size:%s req:%s ms' % (full_uri, size, e)
+        print('visited %s size:%s req:%s ms' % (full_uri, size, e))
 
-    print 'total_time', total_time
-    print 'average on req', total_time / float(pages)
+    print('total_time', total_time)
+    print('average on req', total_time / float(pages))
 
 
 def test_changeset_walk(proj, limit=None):
     repo, proj = _get_repo(proj)
 
-    print 'processing', os.path.join(PROJECT_PATH, proj)
+    print('processing', os.path.join(PROJECT_PATH, proj))
     total_time = 0
 
     cnt = 0
@@ -129,22 +130,22 @@
             break
 
         full_uri = (BASE_URI % raw_cs)
-        print '%s visiting %s\%s' % (cnt, full_uri, i)
+        print('%s visiting %s\%s' % (cnt, full_uri, i))
         s = time.time()
         f = o.open(full_uri)
         size = len(f.read())
         e = time.time() - s
         total_time += e
-        print '%s visited %s\%s size:%s req:%s ms' % (cnt, full_uri, i, size, e)
+        print('%s visited %s\%s size:%s req:%s ms' % (cnt, full_uri, i, size, e))
 
-    print 'total_time', total_time
-    print 'average on req', total_time / float(cnt)
+    print('total_time', total_time)
+    print('average on req', total_time / float(cnt))
 
 
 def test_files_walk(proj, limit=100):
     repo, proj = _get_repo(proj)
 
-    print 'processing', os.path.join(PROJECT_PATH, proj)
+    print('processing', os.path.join(PROJECT_PATH, proj))
     total_time = 0
 
     paths_ = OrderedSet([''])
@@ -171,22 +172,22 @@
 
         file_path = '/'.join((proj, 'files', 'tip', f))
         full_uri = (BASE_URI % file_path)
-        print '%s visiting %s' % (cnt, full_uri)
+        print('%s visiting %s' % (cnt, full_uri))
         s = time.time()
         f = o.open(full_uri)
         size = len(f.read())
         e = time.time() - s
         total_time += e
-        print '%s visited OK size:%s req:%s ms' % (cnt, size, e)
+        print('%s visited OK size:%s req:%s ms' % (cnt, size, e))
 
-    print 'total_time', total_time
-    print 'average on req', total_time / float(cnt)
+    print('total_time', total_time)
+    print('average on req', total_time / float(cnt))
 
 if __name__ == '__main__':
     for path in PROJECTS:
         repo = vcs.get_repo(os.path.join(PROJECT_PATH, path))
         for i in range(PASES):
-            print 'PASS %s/%s' % (i, PASES)
+            print('PASS %s/%s' % (i, PASES))
             test_changelog_walk(repo, pages=80)
             test_changeset_walk(repo, limit=100)
             test_files_walk(repo, limit=100)
--- a/scripts/docs-headings.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/scripts/docs-headings.py	Sun Aug 18 20:25:18 2019 +0200
@@ -4,6 +4,8 @@
 Consistent formatting of rst section titles
 """
 
+from __future__ import print_function
+
 import re
 import subprocess
 
@@ -33,7 +35,7 @@
 def main():
     filenames = subprocess.check_output(['hg', 'loc', 'set:**.rst+kallithea/i18n/how_to']).splitlines()
     for fn in filenames:
-        print 'processing %s' % fn
+        print('processing %s' % fn)
         s = open(fn).read()
 
         # find levels and their styles
@@ -44,11 +46,11 @@
             if style in styles:
                 stylepos = styles.index(style)
                 if stylepos > lastpos + 1:
-                    print 'bad style %r with level %s - was at %s' % (style, stylepos, lastpos)
+                    print('bad style %r with level %s - was at %s' % (style, stylepos, lastpos))
             else:
                 stylepos = len(styles)
                 if stylepos > lastpos + 1:
-                    print 'bad new style %r - expected %r' % (style, styles[lastpos + 1])
+                    print('bad new style %r - expected %r' % (style, styles[lastpos + 1]))
                 else:
                     styles.append(style)
             lastpos = stylepos
@@ -75,7 +77,7 @@
 
         open(fn, 'w').write(s)
 
-    print subprocess.check_output(['hg', 'diff'] + filenames)
+    print(subprocess.check_output(['hg', 'diff'] + filenames))
 
 if __name__ == '__main__':
     main()
--- a/scripts/generate-ini.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/scripts/generate-ini.py	Sun Aug 18 20:25:18 2019 +0200
@@ -3,6 +3,8 @@
 Based on kallithea/lib/paster_commands/template.ini.mako, generate development.ini
 """
 
+from __future__ import print_function
+
 import re
 
 from kallithea.lib import inifile
@@ -52,17 +54,17 @@
 def main():
     # make sure all mako lines starting with '#' (the '##' comments) are marked up as <text>
     makofile = inifile.template_file
-    print 'reading:', makofile
+    print('reading:', makofile)
     mako_org = open(makofile).read()
     mako_no_text_markup = re.sub(r'</?%text>', '', mako_org)
     mako_marked_up = re.sub(r'\n(##.*)', r'\n<%text>\1</%text>', mako_no_text_markup, flags=re.MULTILINE)
     if mako_marked_up != mako_org:
-        print 'writing:', makofile
+        print('writing:', makofile)
         open(makofile, 'w').write(mako_marked_up)
 
     # create ini files
     for fn, settings in ini_files:
-        print 'updating:', fn
+        print('updating:', fn)
         inifile.create(fn, None, settings)
 
 
--- a/scripts/logformat.py	Sun Aug 18 20:27:50 2019 +0200
+++ b/scripts/logformat.py	Sun Aug 18 20:25:18 2019 +0200
@@ -1,5 +1,7 @@
 #!/usr/bin/env python2
 
+from __future__ import print_function
+
 import re
 import sys
 
@@ -38,9 +40,9 @@
 
 if __name__ == '__main__':
     if len(sys.argv) < 2:
-        print 'Cleanup of superfluous % formatting of log statements.'
-        print 'Usage:'
-        print '''  hg revert `hg loc '*.py'|grep -v logformat.py` && scripts/logformat.py `hg loc '*.py'` && hg diff'''
+        print('Cleanup of superfluous % formatting of log statements.')
+        print('Usage:')
+        print('''  hg revert `hg loc '*.py'|grep -v logformat.py` && scripts/logformat.py `hg loc '*.py'` && hg diff''')
         raise SystemExit(1)
 
     for f in sys.argv[1:]: