| 1 |
import glob |
| 2 |
import os |
| 3 |
import re |
| 4 |
import sys |
| 5 |
from functools import total_ordering |
| 6 |
from itertools import dropwhile |
| 7 |
from pathlib import Path |
| 8 |
|
| 9 |
import django |
| 10 |
from django.conf import settings |
| 11 |
from django.core.exceptions import ImproperlyConfigured |
| 12 |
from django.core.files.temp import NamedTemporaryFile |
| 13 |
from django.core.management.base import BaseCommand, CommandError |
| 14 |
from django.core.management.utils import ( |
| 15 |
find_command, |
| 16 |
handle_extensions, |
| 17 |
is_ignored_path, |
| 18 |
popen_wrapper, |
| 19 |
) |
| 20 |
from django.utils.encoding import DEFAULT_LOCALE_ENCODING |
| 21 |
from django.utils.functional import cached_property |
| 22 |
from django.utils.regex_helper import _lazy_re_compile |
| 23 |
from django.utils.text import get_text_list |
| 24 |
from django.utils.translation import templatize |
| 25 |
|
| 26 |
plural_forms_re = _lazy_re_compile( |
| 27 |
r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL |
| 28 |
) |
| 29 |
STATUS_OK = 0 |
| 30 |
NO_LOCALE_DIR = object() |
| 31 |
|
| 32 |
|
| 33 |
def check_programs(*programs): |
| 34 |
for program in programs: |
| 35 |
if find_command(program) is None: |
| 36 |
raise CommandError( |
| 37 |
f"Can't find {program}. Make sure you have GNU gettext tools " |
| 38 |
"0.19 or newer installed." |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
def is_valid_locale(locale): |
| 43 |
return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z0-9].*$", locale) |
| 44 |
|
| 45 |
|
| 46 |
@total_ordering |
| 47 |
class TranslatableFile: |
| 48 |
def __init__(self, dirpath, file_name, locale_dir): |
| 49 |
self.file = file_name |
| 50 |
self.dirpath = dirpath |
| 51 |
self.locale_dir = locale_dir |
| 52 |
|
| 53 |
def __repr__(self): |
| 54 |
return "<%s: %s>" % ( |
| 55 |
self.__class__.__name__, |
| 56 |
os.sep.join([self.dirpath, self.file]), |
| 57 |
) |
| 58 |
|
| 59 |
def __eq__(self, other): |
| 60 |
return self.path == other.path |
| 61 |
|
| 62 |
def __lt__(self, other): |
| 63 |
return self.path < other.path |
| 64 |
|
| 65 |
@property |
| 66 |
def path(self): |
| 67 |
return os.path.join(self.dirpath, self.file) |
| 68 |
|
| 69 |
|
| 70 |
class BuildFile: |
| 71 |
""" |
| 72 |
Represent the state of a translatable file during the build process. |
| 73 |
""" |
| 74 |
|
| 75 |
def __init__(self, command, domain, translatable): |
| 76 |
self.command = command |
| 77 |
self.domain = domain |
| 78 |
self.translatable = translatable |
| 79 |
|
| 80 |
@cached_property |
| 81 |
def is_templatized(self): |
| 82 |
if self.domain == "django": |
| 83 |
file_ext = os.path.splitext(self.translatable.file)[1] |
| 84 |
return file_ext != ".py" |
| 85 |
return False |
| 86 |
|
| 87 |
@cached_property |
| 88 |
def path(self): |
| 89 |
return self.translatable.path |
| 90 |
|
| 91 |
@cached_property |
| 92 |
def work_path(self): |
| 93 |
""" |
| 94 |
Path to a file which is being fed into GNU gettext pipeline. This may |
| 95 |
be either a translatable or its preprocessed version. |
| 96 |
""" |
| 97 |
if not self.is_templatized: |
| 98 |
return self.path |
| 99 |
filename = f"{self.translatable.file}.py" |
| 100 |
return os.path.join(self.translatable.dirpath, filename) |
| 101 |
|
| 102 |
def preprocess(self): |
| 103 |
""" |
| 104 |
Preprocess (if necessary) a translatable file before passing it to |
| 105 |
xgettext GNU gettext utility. |
| 106 |
""" |
| 107 |
if not self.is_templatized: |
| 108 |
return |
| 109 |
|
| 110 |
with open(self.path, encoding="utf-8") as fp: |
| 111 |
src_data = fp.read() |
| 112 |
|
| 113 |
if self.domain == "django": |
| 114 |
content = templatize(src_data, origin=self.path[2:]) |
| 115 |
|
| 116 |
with open(self.work_path, "w", encoding="utf-8") as fp: |
| 117 |
fp.write(content) |
| 118 |
|
| 119 |
def postprocess_messages(self, msgs): |
| 120 |
""" |
| 121 |
Postprocess messages generated by xgettext GNU gettext utility. |
| 122 |
|
| 123 |
Transform paths as if these messages were generated from original |
| 124 |
translatable files rather than from preprocessed versions. |
| 125 |
""" |
| 126 |
if not self.is_templatized: |
| 127 |
return msgs |
| 128 |
|
| 129 |
# Remove '.py' suffix |
| 130 |
if os.name == "nt": |
| 131 |
# Preserve '.\' prefix on Windows to respect gettext behavior |
| 132 |
old_path = self.work_path |
| 133 |
new_path = self.path |
| 134 |
else: |
| 135 |
old_path = self.work_path[2:] |
| 136 |
new_path = self.path[2:] |
| 137 |
|
| 138 |
return re.sub( |
| 139 |
r"^(#: .*)(" + re.escape(old_path) + r")", |
| 140 |
lambda match: match[0].replace(old_path, new_path), |
| 141 |
msgs, |
| 142 |
flags=re.MULTILINE, |
| 143 |
) |
| 144 |
|
| 145 |
def cleanup(self): |
| 146 |
""" |
| 147 |
Remove a preprocessed copy of a translatable file (if any). |
| 148 |
""" |
| 149 |
if self.is_templatized: |
| 150 |
# This check is needed for the case of a symlinked file and its |
| 151 |
# source being processed inside a single group (locale dir); |
| 152 |
# removing either of those two removes both. |
| 153 |
if os.path.exists(self.work_path): |
| 154 |
os.unlink(self.work_path) |
| 155 |
|
| 156 |
|
| 157 |
def normalize_eols(raw_contents): |
| 158 |
""" |
| 159 |
Take a block of raw text that will be passed through str.splitlines() to |
| 160 |
get universal newlines treatment. |
| 161 |
|
| 162 |
Return the resulting block of text with normalized `\n` EOL sequences ready |
| 163 |
to be written to disk using current platform's native EOLs. |
| 164 |
""" |
| 165 |
lines_list = raw_contents.splitlines() |
| 166 |
# Ensure last line has its EOL |
| 167 |
if lines_list and lines_list[-1]: |
| 168 |
lines_list.append("") |
| 169 |
return "\n".join(lines_list) |
| 170 |
|
| 171 |
|
| 172 |
def write_pot_file(potfile, msgs): |
| 173 |
""" |
| 174 |
Write the `potfile` with the `msgs` contents, making sure its format is |
| 175 |
valid. |
| 176 |
""" |
| 177 |
pot_lines = msgs.splitlines() |
| 178 |
if os.path.exists(potfile): |
| 179 |
# Strip the header |
| 180 |
lines = dropwhile(len, pot_lines) |
| 181 |
else: |
| 182 |
lines = [] |
| 183 |
found, header_read = False, False |
| 184 |
for line in pot_lines: |
| 185 |
if not found and not header_read: |
| 186 |
if "charset=CHARSET" in line: |
| 187 |
found = True |
| 188 |
line = line.replace("charset=CHARSET", "charset=UTF-8") |
| 189 |
if not line and not found: |
| 190 |
header_read = True |
| 191 |
lines.append(line) |
| 192 |
msgs = "\n".join(lines) |
| 193 |
# Force newlines of POT files to '\n' to work around |
| 194 |
# https://savannah.gnu.org/bugs/index.php?52395 |
| 195 |
with open(potfile, "a", encoding="utf-8", newline="\n") as fp: |
| 196 |
fp.write(msgs) |
| 197 |
|
| 198 |
|
| 199 |
class Command(BaseCommand): |
| 200 |
help = ( |
| 201 |
"Runs over the entire source tree of the current directory and pulls out all " |
| 202 |
"strings marked for translation. It creates (or updates) a message file in the " |
| 203 |
"conf/locale (in the django tree) or locale (for projects and applications) " |
| 204 |
"directory.\n\nYou must run this command with one of either the --locale, " |
| 205 |
"--exclude, or --all options." |
| 206 |
) |
| 207 |
|
| 208 |
translatable_file_class = TranslatableFile |
| 209 |
build_file_class = BuildFile |
| 210 |
|
| 211 |
requires_system_checks = [] |
| 212 |
|
| 213 |
msgmerge_options = ["-q", "--backup=none", "--previous", "--update"] |
| 214 |
msguniq_options = ["--to-code=utf-8"] |
| 215 |
msgattrib_options = ["--no-obsolete"] |
| 216 |
xgettext_options = ["--from-code=UTF-8", "--add-comments=Translators"] |
| 217 |
|
| 218 |
def add_arguments(self, parser): |
| 219 |
parser.add_argument( |
| 220 |
"--locale", |
| 221 |
"-l", |
| 222 |
default=[], |
| 223 |
action="append", |
| 224 |
help=( |
| 225 |
"Creates or updates the message files for the given locale(s) (e.g. " |
| 226 |
"pt_BR). Can be used multiple times." |
| 227 |
), |
| 228 |
) |
| 229 |
parser.add_argument( |
| 230 |
"--exclude", |
| 231 |
"-x", |
| 232 |
default=[], |
| 233 |
action="append", |
| 234 |
help="Locales to exclude. Default is none. Can be used multiple times.", |
| 235 |
) |
| 236 |
parser.add_argument( |
| 237 |
"--domain", |
| 238 |
"-d", |
| 239 |
default="django", |
| 240 |
help='The domain of the message files (default: "django").', |
| 241 |
) |
| 242 |
parser.add_argument( |
| 243 |
"--all", |
| 244 |
"-a", |
| 245 |
action="store_true", |
| 246 |
help="Updates the message files for all existing locales.", |
| 247 |
) |
| 248 |
parser.add_argument( |
| 249 |
"--extension", |
| 250 |
"-e", |
| 251 |
dest="extensions", |
| 252 |
action="append", |
| 253 |
help='The file extension(s) to examine (default: "html,txt,py", or "js" ' |
| 254 |
'if the domain is "djangojs"). Separate multiple extensions with ' |
| 255 |
"commas, or use -e multiple times.", |
| 256 |
) |
| 257 |
parser.add_argument( |
| 258 |
"--symlinks", |
| 259 |
"-s", |
| 260 |
action="store_true", |
| 261 |
help="Follows symlinks to directories when examining source code " |
| 262 |
"and templates for translation strings.", |
| 263 |
) |
| 264 |
parser.add_argument( |
| 265 |
"--ignore", |
| 266 |
"-i", |
| 267 |
action="append", |
| 268 |
dest="ignore_patterns", |
| 269 |
default=[], |
| 270 |
metavar="PATTERN", |
| 271 |
help="Ignore files or directories matching this glob-style pattern. " |
| 272 |
"Use multiple times to ignore more.", |
| 273 |
) |
| 274 |
parser.add_argument( |
| 275 |
"--no-default-ignore", |
| 276 |
action="store_false", |
| 277 |
dest="use_default_ignore_patterns", |
| 278 |
help=( |
| 279 |
"Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and " |
| 280 |
"'*.pyc'." |
| 281 |
), |
| 282 |
) |
| 283 |
parser.add_argument( |
| 284 |
"--no-wrap", |
| 285 |
action="store_true", |
| 286 |
help="Don't break long message lines into several lines.", |
| 287 |
) |
| 288 |
parser.add_argument( |
| 289 |
"--no-location", |
| 290 |
action="store_true", |
| 291 |
help="Don't write '#: filename:line' lines.", |
| 292 |
) |
| 293 |
parser.add_argument( |
| 294 |
"--add-location", |
| 295 |
choices=("full", "file", "never"), |
| 296 |
const="full", |
| 297 |
nargs="?", |
| 298 |
help=( |
| 299 |
"Controls '#: filename:line' lines. If the option is 'full' " |
| 300 |
"(the default if not given), the lines include both file name " |
| 301 |
"and line number. If it's 'file', the line number is omitted. If " |
| 302 |
"it's 'never', the lines are suppressed (same as --no-location). " |
| 303 |
"--add-location requires gettext 0.19 or newer." |
| 304 |
), |
| 305 |
) |
| 306 |
parser.add_argument( |
| 307 |
"--no-obsolete", |
| 308 |
action="store_true", |
| 309 |
help="Remove obsolete message strings.", |
| 310 |
) |
| 311 |
parser.add_argument( |
| 312 |
"--keep-pot", |
| 313 |
action="store_true", |
| 314 |
help="Keep .pot file after making messages. Useful when debugging.", |
| 315 |
) |
| 316 |
|
| 317 |
def handle(self, *args, **options): |
| 318 |
locale = options["locale"] |
| 319 |
exclude = options["exclude"] |
| 320 |
self.domain = options["domain"] |
| 321 |
self.verbosity = options["verbosity"] |
| 322 |
process_all = options["all"] |
| 323 |
extensions = options["extensions"] |
| 324 |
self.symlinks = options["symlinks"] |
| 325 |
|
| 326 |
ignore_patterns = options["ignore_patterns"] |
| 327 |
if options["use_default_ignore_patterns"]: |
| 328 |
ignore_patterns += ["CVS", ".*", "*~", "*.pyc"] |
| 329 |
self.ignore_patterns = list(set(ignore_patterns)) |
| 330 |
|
| 331 |
# Avoid messing with mutable class variables |
| 332 |
if options["no_wrap"]: |
| 333 |
self.msgmerge_options = self.msgmerge_options[:] + ["--no-wrap"] |
| 334 |
self.msguniq_options = self.msguniq_options[:] + ["--no-wrap"] |
| 335 |
self.msgattrib_options = self.msgattrib_options[:] + ["--no-wrap"] |
| 336 |
self.xgettext_options = self.xgettext_options[:] + ["--no-wrap"] |
| 337 |
if options["no_location"]: |
| 338 |
self.msgmerge_options = self.msgmerge_options[:] + ["--no-location"] |
| 339 |
self.msguniq_options = self.msguniq_options[:] + ["--no-location"] |
| 340 |
self.msgattrib_options = self.msgattrib_options[:] + ["--no-location"] |
| 341 |
self.xgettext_options = self.xgettext_options[:] + ["--no-location"] |
| 342 |
if options["add_location"]: |
| 343 |
arg_add_location = "--add-location=%s" % options["add_location"] |
| 344 |
self.msgmerge_options = self.msgmerge_options[:] + [arg_add_location] |
| 345 |
self.msguniq_options = self.msguniq_options[:] + [arg_add_location] |
| 346 |
self.msgattrib_options = self.msgattrib_options[:] + [arg_add_location] |
| 347 |
self.xgettext_options = self.xgettext_options[:] + [arg_add_location] |
| 348 |
|
| 349 |
self.no_obsolete = options["no_obsolete"] |
| 350 |
self.keep_pot = options["keep_pot"] |
| 351 |
|
| 352 |
if self.domain not in ("django", "djangojs"): |
| 353 |
raise CommandError( |
| 354 |
"currently makemessages only supports domains " |
| 355 |
"'django' and 'djangojs'" |
| 356 |
) |
| 357 |
if self.domain == "djangojs": |
| 358 |
exts = extensions or ["js"] |
| 359 |
else: |
| 360 |
exts = extensions or ["html", "txt", "py"] |
| 361 |
self.extensions = handle_extensions(exts) |
| 362 |
|
| 363 |
if (not locale and not exclude and not process_all) or self.domain is None: |
| 364 |
raise CommandError( |
| 365 |
"Type '%s help %s' for usage information." |
| 366 |
% (os.path.basename(sys.argv[0]), sys.argv[1]) |
| 367 |
) |
| 368 |
|
| 369 |
if self.verbosity > 1: |
| 370 |
self.stdout.write( |
| 371 |
"examining files with the extensions: %s" |
| 372 |
% get_text_list(list(self.extensions), "and") |
| 373 |
) |
| 374 |
|
| 375 |
self.invoked_for_django = False |
| 376 |
self.locale_paths = [] |
| 377 |
self.default_locale_path = None |
| 378 |
if os.path.isdir(os.path.join("conf", "locale")): |
| 379 |
self.locale_paths = [os.path.abspath(os.path.join("conf", "locale"))] |
| 380 |
self.default_locale_path = self.locale_paths[0] |
| 381 |
self.ignore_patterns.append("views/templates/i18n_catalog.js") |
| 382 |
self.invoked_for_django = True |
| 383 |
else: |
| 384 |
if self.settings_available: |
| 385 |
self.locale_paths.extend(settings.LOCALE_PATHS) |
| 386 |
# Allow to run makemessages inside an app dir |
| 387 |
if os.path.isdir("locale"): |
| 388 |
self.locale_paths.append(os.path.abspath("locale")) |
| 389 |
if self.locale_paths: |
| 390 |
self.default_locale_path = self.locale_paths[0] |
| 391 |
os.makedirs(self.default_locale_path, exist_ok=True) |
| 392 |
|
| 393 |
# Build locale list |
| 394 |
looks_like_locale = re.compile(r"[a-z]{2}") |
| 395 |
locale_dirs = filter( |
| 396 |
os.path.isdir, glob.glob("%s/*" % self.default_locale_path) |
| 397 |
) |
| 398 |
all_locales = [ |
| 399 |
lang_code |
| 400 |
for lang_code in map(os.path.basename, locale_dirs) |
| 401 |
if looks_like_locale.match(lang_code) |
| 402 |
] |
| 403 |
|
| 404 |
# Account for excluded locales |
| 405 |
if process_all: |
| 406 |
locales = all_locales |
| 407 |
else: |
| 408 |
locales = locale or all_locales |
| 409 |
locales = set(locales).difference(exclude) |
| 410 |
|
| 411 |
if locales: |
| 412 |
check_programs("msguniq", "msgmerge", "msgattrib") |
| 413 |
|
| 414 |
check_programs("xgettext") |
| 415 |
|
| 416 |
try: |
| 417 |
potfiles = self.build_potfiles() |
| 418 |
|
| 419 |
# Build po files for each selected locale |
| 420 |
for locale in locales: |
| 421 |
if not is_valid_locale(locale): |
| 422 |
# Try to guess what valid locale it could be |
| 423 |
# Valid examples are: en_GB, shi_Latn_MA and nl_NL-x-informal |
| 424 |
|
| 425 |
# Search for characters followed by a non character (i.e. separator) |
| 426 |
match = re.match( |
| 427 |
r"^(?P<language>[a-zA-Z]+)" |
| 428 |
r"(?P<separator>[^a-zA-Z])" |
| 429 |
r"(?P<territory>.+)$", |
| 430 |
locale, |
| 431 |
) |
| 432 |
if match: |
| 433 |
locale_parts = match.groupdict() |
| 434 |
language = locale_parts["language"].lower() |
| 435 |
territory = ( |
| 436 |
locale_parts["territory"][:2].upper() |
| 437 |
+ locale_parts["territory"][2:] |
| 438 |
) |
| 439 |
proposed_locale = f"{language}_{territory}" |
| 440 |
else: |
| 441 |
# It could be a language in uppercase |
| 442 |
proposed_locale = locale.lower() |
| 443 |
|
| 444 |
# Recheck if the proposed locale is valid |
| 445 |
if is_valid_locale(proposed_locale): |
| 446 |
self.stdout.write( |
| 447 |
"invalid locale %s, did you mean %s?" |
| 448 |
% ( |
| 449 |
locale, |
| 450 |
proposed_locale, |
| 451 |
), |
| 452 |
) |
| 453 |
else: |
| 454 |
self.stdout.write("invalid locale %s" % locale) |
| 455 |
|
| 456 |
continue |
| 457 |
if self.verbosity > 0: |
| 458 |
self.stdout.write("processing locale %s" % locale) |
| 459 |
for potfile in potfiles: |
| 460 |
self.write_po_file(potfile, locale) |
| 461 |
finally: |
| 462 |
if not self.keep_pot: |
| 463 |
self.remove_potfiles() |
| 464 |
|
| 465 |
@cached_property |
| 466 |
def gettext_version(self): |
| 467 |
# Gettext tools will output system-encoded bytestrings instead of UTF-8, |
| 468 |
# when looking up the version. It's especially a problem on Windows. |
| 469 |
out, err, status = popen_wrapper( |
| 470 |
["xgettext", "--version"], |
| 471 |
stdout_encoding=DEFAULT_LOCALE_ENCODING, |
| 472 |
) |
| 473 |
m = re.search(r"(\d+)\.(\d+)\.?(\d+)?", out) |
| 474 |
if m: |
| 475 |
return tuple(int(d) for d in m.groups() if d is not None) |
| 476 |
else: |
| 477 |
raise CommandError("Unable to get gettext version. Is it installed?") |
| 478 |
|
| 479 |
@cached_property |
| 480 |
def settings_available(self): |
| 481 |
try: |
| 482 |
settings.LOCALE_PATHS |
| 483 |
except ImproperlyConfigured: |
| 484 |
if self.verbosity > 1: |
| 485 |
self.stderr.write("Running without configured settings.") |
| 486 |
return False |
| 487 |
return True |
| 488 |
|
| 489 |
def build_potfiles(self): |
| 490 |
""" |
| 491 |
Build pot files and apply msguniq to them. |
| 492 |
""" |
| 493 |
file_list = self.find_files(".") |
| 494 |
self.remove_potfiles() |
| 495 |
self.process_files(file_list) |
| 496 |
potfiles = [] |
| 497 |
for path in self.locale_paths: |
| 498 |
potfile = os.path.join(path, "%s.pot" % self.domain) |
| 499 |
if not os.path.exists(potfile): |
| 500 |
continue |
| 501 |
args = ["msguniq"] + self.msguniq_options + [potfile] |
| 502 |
msgs, errors, status = popen_wrapper(args) |
| 503 |
if errors: |
| 504 |
if status != STATUS_OK: |
| 505 |
raise CommandError( |
| 506 |
"errors happened while running msguniq\n%s" % errors |
| 507 |
) |
| 508 |
elif self.verbosity > 0: |
| 509 |
self.stdout.write(errors) |
| 510 |
msgs = normalize_eols(msgs) |
| 511 |
with open(potfile, "w", encoding="utf-8") as fp: |
| 512 |
fp.write(msgs) |
| 513 |
potfiles.append(potfile) |
| 514 |
return potfiles |
| 515 |
|
| 516 |
def remove_potfiles(self): |
| 517 |
for path in self.locale_paths: |
| 518 |
pot_path = os.path.join(path, "%s.pot" % self.domain) |
| 519 |
if os.path.exists(pot_path): |
| 520 |
os.unlink(pot_path) |
| 521 |
|
| 522 |
def find_files(self, root): |
| 523 |
""" |
| 524 |
Get all files in the given root. Also check that there is a matching |
| 525 |
locale dir for each file. |
| 526 |
""" |
| 527 |
all_files = [] |
| 528 |
ignored_roots = [] |
| 529 |
if self.settings_available: |
| 530 |
ignored_roots = [ |
| 531 |
os.path.normpath(p) |
| 532 |
for p in (settings.MEDIA_ROOT, settings.STATIC_ROOT) |
| 533 |
if p |
| 534 |
] |
| 535 |
for dirpath, dirnames, filenames in os.walk( |
| 536 |
root, topdown=True, followlinks=self.symlinks |
| 537 |
): |
| 538 |
for dirname in dirnames[:]: |
| 539 |
if ( |
| 540 |
is_ignored_path( |
| 541 |
os.path.normpath(os.path.join(dirpath, dirname)), |
| 542 |
self.ignore_patterns, |
| 543 |
) |
| 544 |
or os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots |
| 545 |
): |
| 546 |
dirnames.remove(dirname) |
| 547 |
if self.verbosity > 1: |
| 548 |
self.stdout.write("ignoring directory %s" % dirname) |
| 549 |
elif dirname == "locale": |
| 550 |
dirnames.remove(dirname) |
| 551 |
self.locale_paths.insert( |
| 552 |
0, os.path.join(os.path.abspath(dirpath), dirname) |
| 553 |
) |
| 554 |
for filename in filenames: |
| 555 |
file_path = os.path.normpath(os.path.join(dirpath, filename)) |
| 556 |
file_ext = os.path.splitext(filename)[1] |
| 557 |
if file_ext not in self.extensions or is_ignored_path( |
| 558 |
file_path, self.ignore_patterns |
| 559 |
): |
| 560 |
if self.verbosity > 1: |
| 561 |
self.stdout.write( |
| 562 |
"ignoring file %s in %s" % (filename, dirpath) |
| 563 |
) |
| 564 |
else: |
| 565 |
locale_dir = None |
| 566 |
for path in self.locale_paths: |
| 567 |
if os.path.abspath(dirpath).startswith(os.path.dirname(path)): |
| 568 |
locale_dir = path |
| 569 |
break |
| 570 |
locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR |
| 571 |
all_files.append( |
| 572 |
self.translatable_file_class(dirpath, filename, locale_dir) |
| 573 |
) |
| 574 |
return sorted(all_files) |
| 575 |
|
| 576 |
def process_files(self, file_list): |
| 577 |
""" |
| 578 |
Group translatable files by locale directory and run pot file build |
| 579 |
process for each group. |
| 580 |
""" |
| 581 |
file_groups = {} |
| 582 |
for translatable in file_list: |
| 583 |
file_group = file_groups.setdefault(translatable.locale_dir, []) |
| 584 |
file_group.append(translatable) |
| 585 |
for locale_dir, files in file_groups.items(): |
| 586 |
self.process_locale_dir(locale_dir, files) |
| 587 |
|
| 588 |
def process_locale_dir(self, locale_dir, files): |
| 589 |
""" |
| 590 |
Extract translatable literals from the specified files, creating or |
| 591 |
updating the POT file for a given locale directory. |
| 592 |
|
| 593 |
Use the xgettext GNU gettext utility. |
| 594 |
""" |
| 595 |
build_files = [] |
| 596 |
for translatable in files: |
| 597 |
if self.verbosity > 1: |
| 598 |
self.stdout.write( |
| 599 |
"processing file %s in %s" |
| 600 |
% (translatable.file, translatable.dirpath) |
| 601 |
) |
| 602 |
if self.domain not in ("djangojs", "django"): |
| 603 |
continue |
| 604 |
build_file = self.build_file_class(self, self.domain, translatable) |
| 605 |
try: |
| 606 |
build_file.preprocess() |
| 607 |
except UnicodeDecodeError as e: |
| 608 |
self.stdout.write( |
| 609 |
"UnicodeDecodeError: skipped file %s in %s (reason: %s)" |
| 610 |
% ( |
| 611 |
translatable.file, |
| 612 |
translatable.dirpath, |
| 613 |
e, |
| 614 |
) |
| 615 |
) |
| 616 |
continue |
| 617 |
except BaseException: |
| 618 |
# Cleanup before exit. |
| 619 |
for build_file in build_files: |
| 620 |
build_file.cleanup() |
| 621 |
raise |
| 622 |
build_files.append(build_file) |
| 623 |
|
| 624 |
if self.domain == "djangojs": |
| 625 |
args = [ |
| 626 |
"xgettext", |
| 627 |
"-d", |
| 628 |
self.domain, |
| 629 |
"--language=JavaScript", |
| 630 |
"--keyword=gettext_noop", |
| 631 |
"--keyword=gettext_lazy", |
| 632 |
"--keyword=ngettext_lazy:1,2", |
| 633 |
"--keyword=pgettext:1c,2", |
| 634 |
"--keyword=npgettext:1c,2,3", |
| 635 |
"--output=-", |
| 636 |
] |
| 637 |
elif self.domain == "django": |
| 638 |
args = [ |
| 639 |
"xgettext", |
| 640 |
"-d", |
| 641 |
self.domain, |
| 642 |
"--language=Python", |
| 643 |
"--keyword=gettext_noop", |
| 644 |
"--keyword=gettext_lazy", |
| 645 |
"--keyword=ngettext_lazy:1,2", |
| 646 |
"--keyword=pgettext:1c,2", |
| 647 |
"--keyword=npgettext:1c,2,3", |
| 648 |
"--keyword=pgettext_lazy:1c,2", |
| 649 |
"--keyword=npgettext_lazy:1c,2,3", |
| 650 |
"--output=-", |
| 651 |
] |
| 652 |
else: |
| 653 |
return |
| 654 |
|
| 655 |
input_files = [bf.work_path for bf in build_files] |
| 656 |
with NamedTemporaryFile(mode="w+") as input_files_list: |
| 657 |
input_files_list.write("\n".join(input_files)) |
| 658 |
input_files_list.flush() |
| 659 |
args.extend(["--files-from", input_files_list.name]) |
| 660 |
args.extend(self.xgettext_options) |
| 661 |
msgs, errors, status = popen_wrapper(args) |
| 662 |
|
| 663 |
if errors: |
| 664 |
if status != STATUS_OK: |
| 665 |
for build_file in build_files: |
| 666 |
build_file.cleanup() |
| 667 |
raise CommandError( |
| 668 |
"errors happened while running xgettext on %s\n%s" |
| 669 |
% ("\n".join(input_files), errors) |
| 670 |
) |
| 671 |
elif self.verbosity > 0: |
| 672 |
# Print warnings |
| 673 |
self.stdout.write(errors) |
| 674 |
|
| 675 |
if msgs: |
| 676 |
if locale_dir is NO_LOCALE_DIR: |
| 677 |
for build_file in build_files: |
| 678 |
build_file.cleanup() |
| 679 |
file_path = os.path.normpath(build_files[0].path) |
| 680 |
raise CommandError( |
| 681 |
"Unable to find a locale path to store translations for " |
| 682 |
"file %s. Make sure the 'locale' directory exists in an " |
| 683 |
"app or LOCALE_PATHS setting is set." % file_path |
| 684 |
) |
| 685 |
for build_file in build_files: |
| 686 |
msgs = build_file.postprocess_messages(msgs) |
| 687 |
potfile = os.path.join(locale_dir, "%s.pot" % self.domain) |
| 688 |
write_pot_file(potfile, msgs) |
| 689 |
|
| 690 |
for build_file in build_files: |
| 691 |
build_file.cleanup() |
| 692 |
|
| 693 |
def write_po_file(self, potfile, locale): |
| 694 |
""" |
| 695 |
Create or update the PO file for self.domain and `locale`. |
| 696 |
Use contents of the existing `potfile`. |
| 697 |
|
| 698 |
Use msgmerge and msgattrib GNU gettext utilities. |
| 699 |
""" |
| 700 |
basedir = os.path.join(os.path.dirname(potfile), locale, "LC_MESSAGES") |
| 701 |
os.makedirs(basedir, exist_ok=True) |
| 702 |
pofile = os.path.join(basedir, "%s.po" % self.domain) |
| 703 |
|
| 704 |
if os.path.exists(pofile): |
| 705 |
args = ["msgmerge"] + self.msgmerge_options + [pofile, potfile] |
| 706 |
_, errors, status = popen_wrapper(args) |
| 707 |
if errors: |
| 708 |
if status != STATUS_OK: |
| 709 |
raise CommandError( |
| 710 |
"errors happened while running msgmerge\n%s" % errors |
| 711 |
) |
| 712 |
elif self.verbosity > 0: |
| 713 |
self.stdout.write(errors) |
| 714 |
msgs = Path(pofile).read_text(encoding="utf-8") |
| 715 |
else: |
| 716 |
with open(potfile, encoding="utf-8") as fp: |
| 717 |
msgs = fp.read() |
| 718 |
if not self.invoked_for_django: |
| 719 |
msgs = self.copy_plural_forms(msgs, locale) |
| 720 |
msgs = normalize_eols(msgs) |
| 721 |
msgs = msgs.replace( |
| 722 |
"#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % self.domain, "" |
| 723 |
) |
| 724 |
with open(pofile, "w", encoding="utf-8") as fp: |
| 725 |
fp.write(msgs) |
| 726 |
|
| 727 |
if self.no_obsolete: |
| 728 |
args = ["msgattrib"] + self.msgattrib_options + ["-o", pofile, pofile] |
| 729 |
msgs, errors, status = popen_wrapper(args) |
| 730 |
if errors: |
| 731 |
if status != STATUS_OK: |
| 732 |
raise CommandError( |
| 733 |
"errors happened while running msgattrib\n%s" % errors |
| 734 |
) |
| 735 |
elif self.verbosity > 0: |
| 736 |
self.stdout.write(errors) |
| 737 |
|
| 738 |
def copy_plural_forms(self, msgs, locale): |
| 739 |
""" |
| 740 |
Copy plural forms header contents from a Django catalog of locale to |
| 741 |
the msgs string, inserting it at the right place. msgs should be the |
| 742 |
contents of a newly created .po file. |
| 743 |
""" |
| 744 |
django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) |
| 745 |
if self.domain == "djangojs": |
| 746 |
domains = ("djangojs", "django") |
| 747 |
else: |
| 748 |
domains = ("django",) |
| 749 |
for domain in domains: |
| 750 |
django_po = os.path.join( |
| 751 |
django_dir, "conf", "locale", locale, "LC_MESSAGES", "%s.po" % domain |
| 752 |
) |
| 753 |
if os.path.exists(django_po): |
| 754 |
with open(django_po, encoding="utf-8") as fp: |
| 755 |
m = plural_forms_re.search(fp.read()) |
| 756 |
if m: |
| 757 |
plural_form_line = m["value"] |
| 758 |
if self.verbosity > 1: |
| 759 |
self.stdout.write("copying plural forms: %s" % plural_form_line) |
| 760 |
lines = [] |
| 761 |
found = False |
| 762 |
for line in msgs.splitlines(): |
| 763 |
if not found and (not line or plural_forms_re.search(line)): |
| 764 |
line = plural_form_line |
| 765 |
found = True |
| 766 |
lines.append(line) |
| 767 |
msgs = "\n".join(lines) |
| 768 |
break |
| 769 |
return msgs |