1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
|
# Copyright © 2012-2022 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''
command-line interface
'''
import argparse
import concurrent.futures
import functools
import io
import os
import subprocess as ipc
import sys
import tempfile
from lib import check
from lib import ling
from lib import misc
from lib import paths as pathmod
from lib import tags
from lib import terminal
__version__ = '0.27.2'
def initialize_terminal():
if sys.stdout.isatty():
terminal.initialize()
if sys.stdout.errors != 'strict':
return
sys.stdout.reconfigure(errors='backslashreplace')
class Checker(check.Checker):
def tag(self, tagname, *extra):
if tagname in self.options.ignore_tags:
return
try:
tag = tags.get_tag(tagname)
except KeyError:
raise misc.DataIntegrityError(
f'attempted to emit an unknown tag: {tagname!r}'
)
s = tag.format(self.fake_path, *extra, color=True)
print(s)
def check_regular_file(filename, *, options):
checker_instance = Checker(filename, options=options)
checker_instance.check()
def copy_options(options, **update):
kwargs = vars(options)
kwargs.update(update)
return argparse.Namespace(**kwargs)
class UnsupportedFileType(ValueError):
pass
def check_deb(filename, *, options):
if filename.endswith('.deb'):
binary = True
elif filename.endswith('.dsc'):
binary = False
else:
raise UnsupportedFileType
ignore_tags = set(options.ignore_tags)
ignore_tags.add('unknown-file-type')
with tempfile.TemporaryDirectory(prefix='i18nspector.deb.') as tmpdir:
if binary:
ipc.check_call(['dpkg-deb', '-x', filename, tmpdir])
real_root = os.path.join(tmpdir, '')
else:
real_root = os.path.join(tmpdir, 's', '')
ipc.check_call(
['dpkg-source', '--no-copy', '--no-check', '-x', filename, real_root],
stdout=ipc.DEVNULL # dpkg-source would be noisy without this...
)
options = copy_options(options,
ignore_tags=ignore_tags,
fake_root=(real_root, os.path.join(filename, ''))
)
for root, dirs, files in os.walk(tmpdir):
del dirs
for path in files:
path = os.path.join(root, path)
if os.path.islink(path):
continue
if os.path.isfile(path):
check_file(path, options=options)
def check_file(path, *, options):
if options.unpack_deb:
try:
return check_deb(path, options=options)
except UnsupportedFileType:
pass
return check_regular_file(path, options=options)
def check_file_s(path, *, options):
'''
check_file() with captured stdout
'''
orig_stdout = sys.stdout
sys.stdout = io_stdout = io.StringIO()
try:
check_file(path, options=options)
finally:
sys.stdout = orig_stdout
return io_stdout.getvalue()
def check_all(paths, *, options):
if (len(paths) <= 1) or (options.jobs <= 1):
for path in paths:
check_file(path, options=options)
else:
Executor = concurrent.futures.ProcessPoolExecutor
with Executor(max_workers=options.jobs) as executor:
check_file_opt = functools.partial(check_file_s, options=options)
for s in executor.map(check_file_opt, paths):
sys.stdout.write(s)
def get_cpu_count():
try:
sched_getaffinity = os.sched_getaffinity
except AttributeError:
return os.cpu_count() or 1
else:
return len(sched_getaffinity(0))
def parse_jobs(s):
if s == 'auto':
return get_cpu_count()
n = int(s)
if n <= 0:
raise ValueError
return n
parse_jobs.__name__ = 'jobs'
class VersionAction(argparse.Action):
def __init__(self, option_strings, dest=argparse.SUPPRESS):
super().__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
help='show version information and exit'
)
@staticmethod
def _get_rply_version():
rply = check.gettext.intexpr.rply
try:
return rply.__version__
except AttributeError:
# __version__ is available only since rply 0.7.5:
# https://github.com/alex/rply/pull/58
pass
if sys.version_info >= (3, 8):
import importlib.metadata # pylint: disable=import-outside-toplevel,import-error,no-name-in-module
return importlib.metadata.version('rply') # pylint: disable=no-member
try:
import pkg_resources # pylint: disable=import-outside-toplevel
[dist, *rest] = pkg_resources.require('rply')
del rest
except ImportError:
# oh well...
return
assert dist.project_name == 'rply'
return dist.version
def __call__(self, parser, namespace, values, option_string=None):
print(f'{parser.prog} {__version__}')
print('+ Python {0}.{1}.{2}'.format(*sys.version_info)) # pylint: disable=consider-using-f-string
print(f'+ polib {check.polib.__version__}')
rply_version = self._get_rply_version()
if rply_version is not None:
print(f'+ rply {rply_version}')
parser.exit()
def main():
initialize_terminal()
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--version', action=VersionAction)
ap.add_argument('-l', '--language', metavar='LANG', help='assume this language')
ap.add_argument('--unpack-deb', action='store_true', help='allow unpacking Debian packages')
ap.add_argument('-j', '--jobs', type=parse_jobs, metavar='N', default=None, help='use N processes')
ap.add_argument('--parallel', type=int, metavar='N', default=None, help=argparse.SUPPRESS) # renamed as -j/--jobs in 0.25
ap.add_argument('--file-type', metavar='FILE-TYPE', help=argparse.SUPPRESS)
ap.add_argument('--traceback', action='store_true', help=argparse.SUPPRESS)
ap.add_argument('files', metavar='FILE', nargs='+')
options = ap.parse_args()
files = options.files
del options.files
pathmod.check()
if options.language is not None:
try:
language = ling.parse_language(options.language)
language.fix_codes()
except ling.LanguageError:
if options.traceback:
raise
ap.error('invalid language')
language.remove_encoding()
language.remove_nonlinguistic_modifier()
options.language = language
if options.jobs is None:
if options.parallel is not None:
options.jobs = options.parallel
if options.jobs is None:
options.jobs = 1
del options.parallel
options.ignore_tags = set()
options.fake_root = None
Checker.patch_environment()
check_all(files, options=options)
__all__ = ['main']
# vim:ts=4 sts=4 sw=4 et
|