From 0c7a9cea8b5ed381926bef047053c0ec80fa7aa4 Mon Sep 17 00:00:00 2001 From: Takayuki SHIMIZUKAWA Date: Sun, 19 May 2024 17:21:15 +0900 Subject: [PATCH] Modernize formatter: use ruff instead of flake8 (#103) --- .github/workflows/test.yml | 2 +- sphinx_intl/__init__.py | 2 +- sphinx_intl/__main__.py | 3 +- sphinx_intl/basic.py | 78 ++++++----- sphinx_intl/catalog.py | 16 +-- sphinx_intl/commands.py | 260 ++++++++++++++++++++++--------------- sphinx_intl/pycompat.py | 22 ++-- sphinx_intl/transifex.py | 75 ++++++----- tox.ini | 17 ++- 9 files changed, 283 insertions(+), 192 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a07c0f2..1c13930 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -60,7 +60,7 @@ jobs: strategy: fail-fast: false matrix: - env: [flake8, mypy] + env: [lint, mypy] steps: - name: Checkout code diff --git a/sphinx_intl/__init__.py b/sphinx_intl/__init__.py index 8219039..55e4709 100644 --- a/sphinx_intl/__init__.py +++ b/sphinx_intl/__init__.py @@ -1 +1 @@ -__version__ = '2.3.0' +__version__ = "2.3.0" diff --git a/sphinx_intl/__main__.py b/sphinx_intl/__main__.py index e49498b..260f8ec 100644 --- a/sphinx_intl/__main__.py +++ b/sphinx_intl/__main__.py @@ -1,3 +1,4 @@ -if __name__ == '__main__': +if __name__ == "__main__": from sphinx_intl.commands import main + main() diff --git a/sphinx_intl/basic.py b/sphinx_intl/basic.py index 017ec86..a5b7a3f 100644 --- a/sphinx_intl/basic.py +++ b/sphinx_intl/basic.py @@ -10,16 +10,20 @@ # ================================== # utility functions + def get_lang_dirs(path): - dirs = [relpath(d, path) - for d in glob(path+'/[a-z]*') - if os.path.isdir(d) and not d.endswith('pot')] + dirs = [ + relpath(d, path) + for d in glob(path + "/[a-z]*") + if os.path.isdir(d) and not d.endswith("pot") + ] return (tuple(dirs),) # ================================== # commands + def update(locale_dir, pot_dir, languages, line_width=76, ignore_obsolete=False): """ Update specified language's po files from pot. @@ -33,9 +37,9 @@ def update(locale_dir, pot_dir, languages, line_width=76, ignore_obsolete=False) :rtype: dict """ status = { - 'create': 0, - 'update': 0, - 'notchanged': 0, + "create": 0, + "update": 0, + "notchanged": 0, } for dirpath, dirnames, filenames in os.walk(pot_dir): @@ -46,7 +50,7 @@ def update(locale_dir, pot_dir, languages, line_width=76, ignore_obsolete=False) continue basename = relpath(base, pot_dir) for lang in languages: - po_dir = os.path.join(locale_dir, lang, 'LC_MESSAGES') + po_dir = os.path.join(locale_dir, lang, "LC_MESSAGES") po_file = os.path.join(po_dir, basename + ".po") cat_pot = c.load_po(pot_file) if os.path.exists(po_file): @@ -57,20 +61,31 @@ def update(locale_dir, pot_dir, languages, line_width=76, ignore_obsolete=False) if msgids != new_msgids: added = new_msgids - msgids deleted = msgids - new_msgids - status['update'] += 1 - click.echo('Update: {} +{}, -{}'.format( - po_file, len(added), len(deleted))) - c.dump_po(po_file, cat, width=line_width, - ignore_obsolete=ignore_obsolete) + status["update"] += 1 + click.echo( + "Update: {} +{}, -{}".format( + po_file, len(added), len(deleted) + ) + ) + c.dump_po( + po_file, + cat, + width=line_width, + ignore_obsolete=ignore_obsolete, + ) else: - status['notchanged'] += 1 - click.echo(f'Not Changed: {po_file}') + status["notchanged"] += 1 + click.echo(f"Not Changed: {po_file}") else: # new po file - status['create'] += 1 - click.echo(f'Create: {po_file}') + status["create"] += 1 + click.echo(f"Create: {po_file}") cat_pot.locale = lang - c.dump_po(po_file, cat_pot, width=line_width, - ignore_obsolete=ignore_obsolete) + c.dump_po( + po_file, + cat_pot, + width=line_width, + ignore_obsolete=ignore_obsolete, + ) return status @@ -87,7 +102,9 @@ def build(locale_dir, output_dir, languages): for lang in languages: lang_dir = os.path.join(locale_dir, lang) for dirpath, dirnames, filenames in os.walk(lang_dir): - dirpath_output = os.path.join(output_dir, os.path.relpath(dirpath, locale_dir)) + dirpath_output = os.path.join( + output_dir, os.path.relpath(dirpath, locale_dir) + ) for filename in filenames: base, ext = os.path.splitext(filename) @@ -97,10 +114,11 @@ def build(locale_dir, output_dir, languages): mo_file = os.path.join(dirpath_output, base + ".mo") po_file = os.path.join(dirpath, filename) - if (os.path.exists(mo_file) and - os.path.getmtime(mo_file) > os.path.getmtime(po_file)): + if os.path.exists(mo_file) and os.path.getmtime( + mo_file + ) > os.path.getmtime(po_file): continue - click.echo(f'Build: {mo_file}') + click.echo(f"Build: {mo_file}") cat = c.load_po(po_file) c.write_mo(mo_file, cat) @@ -126,17 +144,17 @@ def stat(locale_dir, languages): continue cat = c.load_po(po_file) - r = result[po_file.replace('\\', '/')] = { - 'translated': len(c.translated_entries(cat)), - 'fuzzy': len(c.fuzzy_entries(cat)), - 'untranslated': len(c.untranslated_entries(cat)), + r = result[po_file.replace("\\", "/")] = { + "translated": len(c.translated_entries(cat)), + "fuzzy": len(c.fuzzy_entries(cat)), + "untranslated": len(c.untranslated_entries(cat)), } click.echo( - '{}: {} translated, {} fuzzy, {} untranslated.'.format( + "{}: {} translated, {} fuzzy, {} untranslated.".format( po_file, - r['translated'], - r['fuzzy'], - r['untranslated'], + r["translated"], + r["fuzzy"], + r["untranslated"], ) ) diff --git a/sphinx_intl/catalog.py b/sphinx_intl/catalog.py index 205618c..b78aec2 100644 --- a/sphinx_intl/catalog.py +++ b/sphinx_intl/catalog.py @@ -11,13 +11,13 @@ def load_po(filename, **kwargs): :return: catalog object """ # pre-read to get charset - with open(filename, 'rb') as f: + with open(filename, "rb") as f: cat = pofile.read_po(f) - charset = cat.charset or 'utf-8' + charset = cat.charset or "utf-8" # To decode lines by babel, read po file as binary mode and specify charset for # read_po function. - with open(filename, 'rb') as f: # FIXME: encoding VS charset + with open(filename, "rb") as f: # FIXME: encoding VS charset return pofile.read_po(f, charset=charset, **kwargs) @@ -38,12 +38,12 @@ def dump_po(filename, catalog, **kwargs): # (compatibility) line_width was the original argument used to forward # line width hints into write_po's `width` argument; if provided, # set/override the width value - if 'line_width' in kwargs: - kwargs['width'] = kwargs['line_width'] - del kwargs['line_width'] + if "line_width" in kwargs: + kwargs["width"] = kwargs["line_width"] + del kwargs["line_width"] # Because babel automatically encode strings, file should be open as binary mode. - with open(filename, 'wb') as f: + with open(filename, "wb") as f: pofile.write_po(f, catalog, **kwargs) @@ -57,7 +57,7 @@ def write_mo(filename, catalog, **kwargs): dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) - with open(filename, 'wb') as f: + with open(filename, "wb") as f: mofile.write_mo(f, catalog, **kwargs) diff --git a/sphinx_intl/commands.py b/sphinx_intl/commands.py index 19db813..e4ff672 100644 --- a/sphinx_intl/commands.py +++ b/sphinx_intl/commands.py @@ -1,11 +1,12 @@ """ - sphinx-intl - ~~~~~~~~~~~ - Sphinx utility that make it easy to translate and to apply translation. +sphinx-intl +~~~~~~~~~~~ +Sphinx utility that make it easy to translate and to apply translation. - :copyright: Copyright 2019 by Takayuki SHIMIZUKAWA. - :license: BSD, see LICENSE for details. +:copyright: Copyright 2019 by Takayuki SHIMIZUKAWA. +:license: BSD, see LICENSE for details. """ + import re import os import warnings @@ -18,14 +19,14 @@ from . import transifex from .pycompat import execfile_, relpath -ENVVAR_PREFIX = 'SPHINXINTL' +ENVVAR_PREFIX = "SPHINXINTL" # ================================== # utility functions -def read_config(path, passed_tags): +def read_config(path, passed_tags): tags = Tags() passed_tags = sum(passed_tags, ()) for tag in passed_tags: @@ -50,21 +51,24 @@ def read_config(path, passed_tags): def get_lang_dirs(path): - dirs = [relpath(d, path) - for d in glob(path+'/[a-z]*') - if os.path.isdir(d) and not d.endswith('pot')] + dirs = [ + relpath(d, path) + for d in glob(path + "/[a-z]*") + if os.path.isdir(d) and not d.endswith("pot") + ] return (tuple(dirs),) # ================================== # click options + class LanguagesType(click.ParamType): - name = 'languages' - envvar_list_splitter = ',' + name = "languages" + envvar_list_splitter = "," def convert(self, value, param, ctx): - langs = value.split(',') + langs = value.split(",") return tuple(langs) @@ -72,11 +76,11 @@ def convert(self, value, param, ctx): class TagsType(click.ParamType): - name = 'tags' - envvar_list_splitter = ',' + name = "tags" + envvar_list_splitter = "," def convert(self, value, param, ctx): - tags = value.split(',') + tags = value.split(",") return tuple(tags) @@ -84,93 +88,131 @@ def convert(self, value, param, ctx): option_locale_dir = click.option( - '-d', '--locale-dir', - envvar=ENVVAR_PREFIX + '_LOCALE_DIR', + "-d", + "--locale-dir", + envvar=ENVVAR_PREFIX + "_LOCALE_DIR", type=click.Path(exists=False, file_okay=False), - default='locales', metavar='', show_default=True, - help='locale directories that allow comma separated string. This option ' - 'override locale_dir in conf.py setting if provided. Default is empty ' - 'list.') + default="locales", + metavar="", + show_default=True, + help="locale directories that allow comma separated string. This option " + "override locale_dir in conf.py setting if provided. Default is empty " + "list.", +) option_pot_dir = click.option( - '--pot-dir', '-p', - envvar=ENVVAR_PREFIX + '_POT_DIR', + "--pot-dir", + "-p", + envvar=ENVVAR_PREFIX + "_POT_DIR", type=click.Path(exists=False, file_okay=False), - metavar='', show_default=True, + metavar="", + show_default=True, help="pot files directory which is generated by sphinx. " - "Default is 'pot' directory under '--locale-dir' path.") + "Default is 'pot' directory under '--locale-dir' path.", +) option_output_dir = click.option( - '--output-dir', '-o', - envvar=ENVVAR_PREFIX + '_OUTPUT_DIR', + "--output-dir", + "-o", + envvar=ENVVAR_PREFIX + "_OUTPUT_DIR", type=click.Path(exists=False, file_okay=False), - metavar='', show_default=True, + metavar="", + show_default=True, help="mo files directory where files are written. " - "Default is to match the '--locale-dir' path.") + "Default is to match the '--locale-dir' path.", +) option_tag = click.option( - '-t', '--tag', - envvar=ENVVAR_PREFIX + '_TAG', - type=TAGS, metavar='', show_default=True, + "-t", + "--tag", + envvar=ENVVAR_PREFIX + "_TAG", + type=TAGS, + metavar="", + show_default=True, multiple=True, - help="Pass tags to conf.py, as same as passed to sphinx-build -t option.") + help="Pass tags to conf.py, as same as passed to sphinx-build -t option.", +) option_language = click.option( - '-l', '--language', - envvar=ENVVAR_PREFIX + '_LANGUAGE', - type=LANGUAGES, metavar='', show_default=True, + "-l", + "--language", + envvar=ENVVAR_PREFIX + "_LANGUAGE", + type=LANGUAGES, + metavar="", + show_default=True, multiple=True, - help="Target language to update po files. Default is ALL.") + help="Target language to update po files. Default is ALL.", +) option_line_width = click.option( - '-w', '--line-width', - envvar=ENVVAR_PREFIX + '_LINE_WIDTH', - type=int, default=76, metavar='', show_default=True, + "-w", + "--line-width", + envvar=ENVVAR_PREFIX + "_LINE_WIDTH", + type=int, + default=76, + metavar="", + show_default=True, multiple=False, - help='The maximum line width for the po files, 0 or a negative number ' - 'disable line wrapping') + help="The maximum line width for the po files, 0 or a negative number " + "disable line wrapping", +) option_no_obsolete = click.option( - '--no-obsolete', - envvar=ENVVAR_PREFIX + '_NO_OBSOLETE', - is_flag=True, default=False, - help='Remove obsolete #~ messages.') + "--no-obsolete", + envvar=ENVVAR_PREFIX + "_NO_OBSOLETE", + is_flag=True, + default=False, + help="Remove obsolete #~ messages.", +) option_transifex_token = click.option( - '--transifex-token', - envvar=ENVVAR_PREFIX + '_TRANSIFEX_TOKEN', - type=str, metavar='', required=True, - help="Your transifex token. (DEPRECATED)") + "--transifex-token", + envvar=ENVVAR_PREFIX + "_TRANSIFEX_TOKEN", + type=str, + metavar="", + required=True, + help="Your transifex token. (DEPRECATED)", +) option_transifex_organization_name = click.option( - '--transifex-organization-name', - envvar=ENVVAR_PREFIX + '_TRANSIFEX_ORGANIZATION_NAME', - type=str, metavar='', required=True, - help="Your transifex organization name.") + "--transifex-organization-name", + envvar=ENVVAR_PREFIX + "_TRANSIFEX_ORGANIZATION_NAME", + type=str, + metavar="", + required=True, + help="Your transifex organization name.", +) option_transifex_project_name = click.option( - '--transifex-project-name', - envvar=ENVVAR_PREFIX + '_TRANSIFEX_PROJECT_NAME', - type=str, metavar='', required=True, - help="Your transifex project name.") + "--transifex-project-name", + envvar=ENVVAR_PREFIX + "_TRANSIFEX_PROJECT_NAME", + type=str, + metavar="", + required=True, + help="Your transifex project name.", +) # ================================== # commands + @click.group() @click.option( - '-c', '--config', + "-c", + "--config", type=click.Path(exists=True, file_okay=True, dir_okay=False), - default=None, metavar='', - help='Sphinx conf.py file to read a locale directory setting.') + default=None, + metavar="", + help="Sphinx conf.py file to read a locale directory setting.", +) @option_tag @click.pass_context def main(ctx, config, tag): # load conf.py ctx.config = config if ctx.config is None: - for c in ('conf.py', 'source/conf.py'): + for c in ("conf.py", "source/conf.py"): if os.path.exists(c): ctx.config = c break @@ -179,44 +221,46 @@ def main(ctx, config, tag): ctx.locale_dir = None if ctx.config: cfg = read_config(ctx.config, tag) - if 'locale_dirs' in cfg: + if "locale_dirs" in cfg: ctx.locale_dir = os.path.join( - os.path.dirname(ctx.config), cfg['locale_dirs'][0]) + os.path.dirname(ctx.config), cfg["locale_dirs"][0] + ) # for pot_dir ctx.pot_dir = None - for d in ('_build/gettext', 'build/gettext', - '_build/locale', 'build/locale'): + for d in ("_build/gettext", "build/gettext", "_build/locale", "build/locale"): if os.path.exists(d): ctx.pot_dir = d break # for transifex_project_name ctx.transifex_project_name = None - target = os.path.normpath('.tx/config') + target = os.path.normpath(".tx/config") if os.path.exists(target): - matched = re.search(r'\[(.*)\..*\]', open(target).read()) + matched = re.search(r"\[(.*)\..*\]", open(target).read()) if matched: ctx.transifex_project_name = matched.groups()[0] click.echo( - 'Project name loaded from .tx/config: {}'.format( - ctx.transifex_project_name)) + "Project name loaded from .tx/config: {}".format( + ctx.transifex_project_name + ) + ) ctx.default_map = { - 'update': { - 'locale_dir': ctx.locale_dir, - 'pot_dir': ctx.pot_dir, + "update": { + "locale_dir": ctx.locale_dir, + "pot_dir": ctx.pot_dir, }, - 'build': { - 'locale_dir': ctx.locale_dir, + "build": { + "locale_dir": ctx.locale_dir, }, - 'stat': { - 'locale_dir': ctx.locale_dir, + "stat": { + "locale_dir": ctx.locale_dir, }, - 'update-txconfig-resources': { - 'locale_dir': ctx.locale_dir, - 'pot_dir': ctx.pot_dir, - 'transifex_project_name': ctx.transifex_project_name, + "update-txconfig-resources": { + "locale_dir": ctx.locale_dir, + "pot_dir": ctx.pot_dir, + "transifex_project_name": ctx.transifex_project_name, }, } @@ -237,23 +281,27 @@ def update(locale_dir, pot_dir, language, line_width, no_obsolete): sphinx-intl update -l de,ja """ if not pot_dir: - pot_dir = os.path.join(locale_dir, 'pot') + pot_dir = os.path.join(locale_dir, "pot") if not os.path.exists(pot_dir): - msg = ("%(pot_dir)r does not exist. Please specify pot directory with " - "-p option, or preparing your pot files in %(pot_dir)r." - % locals()) - raise click.BadParameter(msg, param_hint='pot_dir') + msg = ( + "%(pot_dir)r does not exist. Please specify pot directory with " + "-p option, or preparing your pot files in %(pot_dir)r." % locals() + ) + raise click.BadParameter(msg, param_hint="pot_dir") if not language: language = get_lang_dirs(locale_dir) languages = sum(language, ()) # flatten if not languages: - msg = ("No languages are found. Please specify language with -l " - "option, or preparing language directories under %(locale_dir)r " - "directory." - % locals()) - raise click.BadParameter(msg, param_hint='language') - - basic.update(locale_dir, pot_dir, languages, line_width, ignore_obsolete=no_obsolete) + msg = ( + "No languages are found. Please specify language with -l " + "option, or preparing language directories under %(locale_dir)r " + "directory." % locals() + ) + raise click.BadParameter(msg, param_hint="language") + + basic.update( + locale_dir, pot_dir, languages, line_width, ignore_obsolete=no_obsolete + ) @main.command() @@ -269,8 +317,8 @@ def build(locale_dir, output_dir, language): languages = sum(language, ()) # flatten if not output_dir or ( - os.path.exists(output_dir) and - os.path.samefile(locale_dir, output_dir)): + os.path.exists(output_dir) and os.path.samefile(locale_dir, output_dir) + ): output_dir = locale_dir basic.build(locale_dir, output_dir, languages) @@ -289,7 +337,7 @@ def stat(locale_dir, language): basic.stat(locale_dir, languages) -@main.command('create-transifexrc') +@main.command("create-transifexrc") @option_transifex_token def create_transifexrc(transifex_token): """ @@ -306,7 +354,7 @@ def create_transifexrc(transifex_token): transifex.create_transifexrc(transifex_token) -@main.command('create-txconfig') +@main.command("create-txconfig") def create_txconfig(): """ Create `./.tx/config` @@ -314,22 +362,24 @@ def create_txconfig(): transifex.create_txconfig() -@main.command('update-txconfig-resources') +@main.command("update-txconfig-resources") @option_transifex_organization_name @option_transifex_project_name @option_locale_dir @option_pot_dir -def update_txconfig_resources(transifex_organization_name, transifex_project_name, - locale_dir, pot_dir): +def update_txconfig_resources( + transifex_organization_name, transifex_project_name, locale_dir, pot_dir +): """ Update resource sections of `./.tx/config`. """ if not pot_dir: - pot_dir = os.path.join(locale_dir, 'pot') + pot_dir = os.path.join(locale_dir, "pot") - transifex.update_txconfig_resources(transifex_organization_name, transifex_project_name, - locale_dir, pot_dir) + transifex.update_txconfig_resources( + transifex_organization_name, transifex_project_name, locale_dir, pot_dir + ) -if __name__ == '__main__': +if __name__ == "__main__": main(auto_envvar_prefix=ENVVAR_PREFIX) diff --git a/sphinx_intl/pycompat.py b/sphinx_intl/pycompat.py index 1505f79..257908c 100644 --- a/sphinx_intl/pycompat.py +++ b/sphinx_intl/pycompat.py @@ -1,6 +1,7 @@ """ Python compatibility functions. """ + import sys import os import warnings @@ -24,11 +25,12 @@ def relpath(path: str, start: str = os.curdir) -> str: def convert_with_2to3(filepath: str) -> str: from lib2to3.refactor import RefactoringTool, get_fixers_from_package from lib2to3.pgen2.parse import ParseError - fixers = get_fixers_from_package('lib2to3.fixes') + + fixers = get_fixers_from_package("lib2to3.fixes") refactoring_tool = RefactoringTool(fixers) source = refactoring_tool._read_python_source(filepath)[0] try: - tree = refactoring_tool.refactor_string(source, 'conf.py') + tree = refactoring_tool.refactor_string(source, "conf.py") except ParseError as err: # do not propagate lib2to3 exceptions lineno, offset = err.context[1] @@ -38,20 +40,22 @@ def convert_with_2to3(filepath: str) -> str: def execfile_(filepath: str, _globals: Any, open: Callable = open) -> None: - with open(filepath, 'rb') as f: + with open(filepath, "rb") as f: source = f.read() # compile to a code object, handle syntax errors filepath_enc = filepath.encode(fs_encoding) try: - code = compile(source, filepath_enc, 'exec') + code = compile(source, filepath_enc, "exec") except SyntaxError: # maybe the file uses 2.x syntax; try to refactor to # 3.x syntax using 2to3 source = convert_with_2to3(filepath) - code = compile(source, filepath_enc, 'exec') - warnings.warn('Support for evaluating Python 2 syntax is deprecated ' - 'and will be removed in sphinx-intl 4.0. ' - 'Convert %s to Python 3 syntax.', - source=filepath) + code = compile(source, filepath_enc, "exec") + warnings.warn( + "Support for evaluating Python 2 syntax is deprecated " + "and will be removed in sphinx-intl 4.0. " + "Convert %s to Python 3 syntax.", + source=filepath, + ) exec(code, _globals) diff --git a/sphinx_intl/transifex.py b/sphinx_intl/transifex.py index c86ba93..ea28ccd 100644 --- a/sphinx_intl/transifex.py +++ b/sphinx_intl/transifex.py @@ -21,8 +21,8 @@ # resource names are reserved slugs, Transifex will reply with an error on these # resource names. IGNORED_RESOURCE_NAMES = ( - 'glossary', - 'settings', + "glossary", + "settings", ) TRANSIFEXRC_TEMPLATE = """\ @@ -40,22 +40,23 @@ # ================================== # utility functions + def normalize_resource_name(name): # replace path separator with '--' - name = re.sub(r'[\\/]', '--', name) + name = re.sub(r"[\\/]", "--", name) # replace unusable characters (not: -, _ ascii, digit) with '_' - name = re.sub(r'[^\-\w]', '_', name) + name = re.sub(r"[^\-\w]", "_", name) # append `_` for ignored resource names while name in IGNORED_RESOURCE_NAMES: - name += '_' + name += "_" return name def check_transifex_cli_installed(): - tx_cli_url = 'https://raw.githubusercontent.com/transifex/cli/master/install.sh' + tx_cli_url = "https://raw.githubusercontent.com/transifex/cli/master/install.sh" if not which("tx"): msg = textwrap.dedent(f"""\ Could not run "tx". @@ -99,14 +100,15 @@ def check_transifex_cli_installed(): # ================================== # commands + def create_transifexrc(transifex_token): """ Create `$HOME/.transifexrc` """ - target = os.path.normpath(os.path.expanduser('~/.transifexrc')) + target = os.path.normpath(os.path.expanduser("~/.transifexrc")) if os.path.exists(target): - click.echo(f'{target} already exists, skipped.') + click.echo(f"{target} already exists, skipped.") return if not transifex_token: @@ -114,56 +116,63 @@ def create_transifexrc(transifex_token): You need a transifex token by command option or environment. command option: --transifex-token """) - raise click.BadParameter(msg, param_hint='transifex_token') + raise click.BadParameter(msg, param_hint="transifex_token") - with open(target, 'w') as rc: + with open(target, "w") as rc: rc.write(TRANSIFEXRC_TEMPLATE % locals()) - click.echo(f'Create: {target}') + click.echo(f"Create: {target}") def create_txconfig(): """ Create `./.tx/config` """ - target = os.path.normpath('.tx/config') + target = os.path.normpath(".tx/config") if os.path.exists(target): - click.echo(f'{target} already exists, skipped.') + click.echo(f"{target} already exists, skipped.") return - if not os.path.exists('.tx'): - os.mkdir('.tx') + if not os.path.exists(".tx"): + os.mkdir(".tx") - with open(target, 'w') as f: + with open(target, "w") as f: f.write(TXCONFIG_TEMPLATE) - click.echo(f'Create: {target}') + click.echo(f"Create: {target}") -def update_txconfig_resources(transifex_organization_name, transifex_project_name, - locale_dir, pot_dir): +def update_txconfig_resources( + transifex_organization_name, transifex_project_name, locale_dir, pot_dir +): """ Update resource sections of `./.tx/config`. """ check_transifex_cli_installed() cmd_tmpl = ( - 'tx', - 'add', - '--organization', '%(transifex_organization_name)s', - '--project', '%(transifex_project_name)s', - '--resource', '%(resource_slug)s', - '--resource-name', '%(resource_name)s', - '--file-filter', '%(locale_dir)s//LC_MESSAGES/%(resource_path)s.po', - '--type', 'PO', - '%(pot_dir)s/%(resource_path)s.pot', + "tx", + "add", + "--organization", + "%(transifex_organization_name)s", + "--project", + "%(transifex_project_name)s", + "--resource", + "%(resource_slug)s", + "--resource-name", + "%(resource_name)s", + "--file-filter", + "%(locale_dir)s//LC_MESSAGES/%(resource_path)s.po", + "--type", + "PO", + "%(pot_dir)s/%(resource_path)s.pot", ) # convert transifex_project_name to internal name - transifex_project_name = transifex_project_name.replace(' ', '-') - transifex_project_name = re.sub(r'[^\-_\w]', '', transifex_project_name) + transifex_project_name = transifex_project_name.replace(" ", "-") + transifex_project_name = re.sub(r"[^\-_\w]", "", transifex_project_name) pot_dir = Path(pot_dir) - pot_paths = sorted(pot_dir.glob('**/*.pot')) + pot_paths = sorted(pot_dir.glob("**/*.pot")) with click.progressbar( pot_paths, length=len(pot_paths), @@ -172,7 +181,7 @@ def update_txconfig_resources(transifex_organization_name, transifex_project_nam item_show_func=lambda p: str(p), ) as progress_bar: for pot_path in progress_bar: - resource_path = str(pot_path.relative_to(pot_dir).with_suffix('')) + resource_path = str(pot_path.relative_to(pot_dir).with_suffix("")) resource_slug = resource_name = normalize_resource_name(resource_path) pot = load_po(str(pot_path)) if len(pot): @@ -180,4 +189,4 @@ def update_txconfig_resources(transifex_organization_name, transifex_project_nam cmd = [arg % lv for arg in cmd_tmpl] subprocess.check_output(cmd, shell=False) else: - click.echo(f'{pot_path} is empty, skipped') + click.echo(f"{pot_path} is empty, skipped") diff --git a/tox.ini b/tox.ini index 0f91051..5c4703c 100644 --- a/tox.ini +++ b/tox.ini @@ -1,7 +1,7 @@ [tox] envlist = py{38,39,310,311,312,313}, - flake8, + lint, mypy [gh-actions] @@ -21,10 +21,19 @@ setenv = commands= py.test {posargs} -[testenv:flake8] +[testenv:lint] usedevelop=True -deps=flake8 -commands=flake8 sphinx_intl +deps=ruff +commands= + ruff check sphinx_intl + ruff format --check sphinx_intl + +[testenv:format] +usedevelop=True +deps=ruff +commands= + ruff check --fix sphinx_intl + ruff format sphinx_intl [testenv:mypy] usedevelop=True