Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update python scrips to Python 3.x #1592

Merged
merged 1 commit into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 32 additions & 22 deletions VersionManager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#! /usr/bin/env python2
#! /usr/bin/env python3

"""
A script that manages the VERSION of gregorio.
Expand All @@ -23,7 +23,6 @@
along with Gregorio. If not, see <http://www.gnu.org/licenses/>.
"""

from __future__ import print_function

import sys
import re
Expand All @@ -35,8 +34,6 @@
import linecache
from datetime import date

from distutils.util import strtobool

locale.setlocale(locale.LC_TIME, 'C')

os.chdir(sys.path[0])
Expand Down Expand Up @@ -170,6 +167,19 @@
"windows/uninstall.lua",
]

def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
if val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
raise ValueError(f'invalid truth value: {val}')

def get_parser():
"Return command line parser"
parser = argparse.ArgumentParser(
Expand Down Expand Up @@ -218,7 +228,7 @@ def get_parser():
dest='release')
return parser

class Version(object):
class Version():
"Class for version manipulation."

def __init__(self, versionfile):
Expand Down Expand Up @@ -259,19 +269,17 @@ def fetch_version_debian_git(self):
['git', 'rev-parse', '--short', 'HEAD'])
self.short_tag = self.short_tag.strip('\n')
self.date = time.strftime("%Y%m%d%H%M%S")
print("{0}+git{1}+{2}".format(self.version.replace('-', '~'),
self.date, self.short_tag))
print(f"{self.version.replace('-', '~')}+git{self.date}+{self.short_tag}")
sys.exit(0)

def update_version(self, newversion):
"Update self.version and .gregorio-version with the new version."
self.version = newversion
self.filename_version = self.filename_version_from_version(newversion)
self.binary_version = self.binary_version_from_version(newversion)
print('Updating {0} with the new version: {1}\n'.format(
self.versionfile, self.version))
with open(self.versionfile, 'w') as verfile:
verfile.write('{0}\n{1}'.format(self.version, CURRENTYEAR))
print(f'Updating {self.versionfile} with the new version: {self.version}\n')
with open(self.versionfile, 'w', encoding='utf-8') as verfile:
verfile.write(f'{self.version}\n{CURRENTYEAR}')
verfile.write('\n\n*** Do not modify this file. ***\n')
verfile.write('Use VersionManager.py to change the version.\n')

Expand All @@ -281,11 +289,11 @@ def replace_version(version_obj):
newver_filename = version_obj.filename_version
newbinver = version_obj.binary_version
today = date.today()
print('Updating source files to version {0}\n'.format(newver))
print(f'Updating source files to version {newver}\n')
for myfile in GREGORIO_FILES:
result = []
following_line_filename = False
with open(myfile, 'r') as infile:
with open(myfile, 'r', encoding='utf-8') as infile:
for line in infile:
if 'AC_INIT([' in line:
result.append(re.sub(r'(\d+\.\d+\.\d+(?:[-+~]\w+)*)', newver, line, 1))
Expand All @@ -306,7 +314,8 @@ def replace_version(version_obj):
result.append(re.sub(r'(\d+\/\d+/\d+)', today.strftime("%Y/%m/%d"), newline, 1))
elif 'PARSE_VERSION_DATE' in line:
newline = re.sub(r'(\d+\.\d+\.\d+(?:[-+~]\w+)*)', newver, line, 1)
result.append(re.sub(r'(\d{1,2} [A-Z][a-z]+ \d{4})', today.strftime("%-d %B %Y"), newline, 1))
result.append(re.sub(r'(\d{1,2} [A-Z][a-z]+ \d{4})',
today.strftime("%-d %B %Y"), newline, 1))
elif 'FILEVERSION' in line:
result.append(re.sub(r'\d+,\d+,\d+,\d+', newbinver, line, 1))
elif 'PRODUCTVERSION' in line:
Expand All @@ -319,13 +328,14 @@ def replace_version(version_obj):
following_line_filename = False
else:
result.append(line)
with open(myfile, 'w') as outfile:
with open(myfile, 'w', encoding='utf-8') as outfile:
outfile.write(''.join(result))
sys.exit(0)

def update_changelog(newver,upgradetype):
def update_changelog(newver, upgradetype):
"Insert the version number into CHANGELOG"
today = date.today()
with open('CHANGELOG.md', 'r') as infile:
with open('CHANGELOG.md', 'r', encoding='utf-8') as infile:
result = []
develop = False
for line in infile:
Expand Down Expand Up @@ -361,17 +371,17 @@ def update_changelog(newver,upgradetype):
print("I didn't find a unreleased develop section.")
print("Non-patch releases should be based on develop branch.")
sys.exit(1)
with open('CHANGELOG.md', 'w') as outfile:
with open('CHANGELOG.md', 'w', encoding='utf-8') as outfile:
outfile.write(''.join(result))

def confirm_replace(oldver, newver):
"Query the user to confirm action"
query = 'Update version from {0} --> {1} [y/n]?'.format(oldver, newver)
query = f'Update version from {oldver} --> {newver} [y/n]?'
print(query)
consent = None
while True:
try:
consent = strtobool(raw_input().lower())
consent = strtobool(input().lower())
break
except ValueError:
print('Answer with y or n.')
Expand Down Expand Up @@ -478,7 +488,7 @@ def year_range(matchobj):
print('Updating copyright year.')
for myfile in COPYRIGHT_FILES:
result = []
with open(myfile, 'r') as infile:
with open(myfile, 'r', encoding='utf-8') as infile:
for line in infile:
if re.search(r'[C|c]opyright.*Gregorio Project', line):
result.append(re.sub(r'(\d{4}-)?(\d{4})', year_range, line))
Expand All @@ -490,7 +500,7 @@ def year_range(matchobj):
result.append(re.sub(r'(\d{4}-)?(\d{4})', year_range, line))
else:
result.append(line)
with open(myfile, 'w') as outfile:
with open(myfile, 'w', encoding='utf-8') as outfile:
outfile.write(''.join(result))

def main():
Expand Down
21 changes: 12 additions & 9 deletions contrib/checkSyllabation.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@

"""


import os
import sys
import re
import glob
import argparse
import pyphen
import os
import glob


DEFAULT_OUTFILE = False
if os.name == 'nt':
Expand All @@ -62,7 +64,8 @@ def get_parser():
return parser

def deacc(accstr):
return accstr.replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('ý', 'y').replace('́', '').replace('ǽ', 'æ')
"Remove accents from vowels"
return accstr.replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('ý', 'y').replace('́', '').replace('ǽ', 'æ')

def checkwords(words_list, hyphenator):
errors = []
Expand Down Expand Up @@ -100,15 +103,15 @@ def get_words_list(gabc_content):
return gabc_content.split()

def get_file_list(path):
"Generate list of files to parse"
if os.path.isfile(path):
return [path]
elif os.path.isdir(path):
if os.path.isdir(path):
files = glob.glob(os.path.join(path, '**/*.gabc'), recursive=True)
files = sorted(files)
return files
else:
print('Error! Cannot find '+path, file=sys.stderr)
sys.exit(1)
print(f'Error! Cannot find {path}', file=sys.stderr)
sys.exit(1)

def check_file(filepath, hyphenator, outfd, report_no_error=False):
words_list = []
Expand Down Expand Up @@ -139,8 +142,8 @@ def main():
outfd = open(args.outfile, 'w', encoding='utf8')
file_list = get_file_list(args.path)
nb_errors = 0
for f in file_list:
nb_errors += check_file(f, hyphenator, outfd, args.verbose)
for filename in file_list:
nb_errors += check_file(filename, hyphenator, outfd, args.verbose)
if len(file_list) > 1 and nb_errors > 0:
outfd.write('Total errors: '+str(nb_errors)+'\n')
elif nb_errors == 0 and not args.verbose:
Expand Down
7 changes: 3 additions & 4 deletions fonts/convertsfdtottf.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@
"""


from __future__ import print_function

import getopt, sys
import sys
import getopt
import fontforge


Expand Down Expand Up @@ -64,7 +63,7 @@ def main():
usage()
sys.exit(2)
if args[0][-3:] == "sfd":
outputfile = "%s.ttf" % args[0][:-4]
outputfile = f'{args[0][:-4]}.ttf'
inputfile = args[0]
else:
usage()
Expand Down
5 changes: 2 additions & 3 deletions fonts/simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@
"""


from __future__ import print_function

import getopt, sys
import sys
import getopt
import fontforge


Expand Down
11 changes: 5 additions & 6 deletions fonts/squarize.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
own glyphs from it.
"""

from __future__ import print_function

import sys
import os
Expand Down Expand Up @@ -68,7 +67,7 @@
# defines the maximal interval between two notes, the bigger this number is,
# the more glyphs you'll have to generate
MAX_INTERVAL = 5
ALL_AMBITUS = range(1, MAX_INTERVAL + 1)
ALL_AMBITUS = list(range(1, MAX_INTERVAL + 1))
AMBITUS_ONE_ONLY = [ 1 ]

# this dictionary must have a value for 0 to 14 (the maximum overall ambitus)
Expand Down Expand Up @@ -229,7 +228,7 @@ def set_glyph_name(name):
global all_glyph_names, newfont, glyphnumber
if glyphnumber in newfont:
if name in all_glyph_names:
print("ERROR: duplicate glyph name [%s]" % name, file=sys.stderr)
print(f'ERROR: duplicate glyph name [{name}]', file=sys.stderr)
sys.exit(1)
else:
all_glyph_names[name] = True
Expand Down Expand Up @@ -440,7 +439,7 @@ def glyph_exists(glyph_name):
result = True
try:
oldfont.selection.select(glyph_name + '')
except Exception as ex:
except Exception:
result = False
GLYPH_EXISTS[glyph_name] = result
return result
Expand Down Expand Up @@ -1126,7 +1125,7 @@ def measures():
def hepisema():
"Creates horizontal episemata."
message("horizontal episema")
for target, source in HEPISEMA_GLYPHS.items():
for target, source in list(HEPISEMA_GLYPHS.items()):
write_hepisema(get_width(source), target)
write_hepisema(get_width(source) * 2.0 / 3.0, target + "Reduced")
reduction = get_width('PunctumSmall')
Expand Down Expand Up @@ -2486,7 +2485,7 @@ def scandicus():
write_all_scandicus('rdeminutus', L_DEMINUTUS)

def write_all_scandicus(last_glyph, lique=L_NOTHING, i_range=ALL_AMBITUS,
j_range=ALL_AMBITUS):
j_range=ALL_AMBITUS):
for i in i_range:
for j in j_range:
write_scandicus(i, j, last_glyph, lique)
Expand Down
4 changes: 2 additions & 2 deletions fonts/stemsschemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,6 @@ def get_stem_schema(schemaname, font_config):
"""
if schemaname == 'default':
return get_stem_schema_default(font_config)
elif schemaname == 'solesmes':
if schemaname == 'solesmes':
return get_stem_schema_solesmes(font_config)
print('impossible to find schema %s, quitting' % schemaname)
print(f'impossible to find schema {schemaname}, quitting')