Merge pull request #761 from mwhudson/still-better-i18n
more work towards being able to provide good translations
This commit is contained in:
commit
a9dd3757f1
2
Makefile
2
Makefile
|
@ -50,7 +50,7 @@ lint: flake8
|
||||||
|
|
||||||
flake8:
|
flake8:
|
||||||
@echo 'tox -e flake8' is preferred to 'make flake8'
|
@echo 'tox -e flake8' is preferred to 'make flake8'
|
||||||
$(PYTHON) -m flake8 $(CHECK_DIRS)
|
$(PYTHON) -m flake8 $(CHECK_DIRS) --exclude gettext38.py
|
||||||
|
|
||||||
unit:
|
unit:
|
||||||
echo "Running unit tests..."
|
echo "Running unit tests..."
|
||||||
|
|
71
setup.py
71
setup.py
|
@ -22,18 +22,64 @@ subiquity
|
||||||
Ubuntu Server Installer
|
Ubuntu Server Installer
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from setuptools import setup, find_packages
|
import distutils.cmd
|
||||||
|
import distutils.command.build
|
||||||
|
import distutils.spawn
|
||||||
|
import glob
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
setup_kwargs = {}
|
from setuptools import setup, find_packages
|
||||||
# dpkg build uses build and install, tox uses sdist
|
|
||||||
if 'SUBIQUITY_NO_I18N' not in os.environ:
|
|
||||||
from DistUtilsExtra.command import build_extra
|
class build_i18n(distutils.cmd.Command):
|
||||||
from DistUtilsExtra.command import build_i18n
|
|
||||||
setup_kwargs['cmdclass'] = {'build': build_extra.build_extra,
|
user_options = []
|
||||||
'build_i18n': build_i18n.build_i18n}
|
|
||||||
|
def initialize_options(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def finalize_options(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
data_files = self.distribution.data_files
|
||||||
|
|
||||||
|
with open('po/POTFILES.in') as in_fp:
|
||||||
|
with open('po/POTFILES.in.tmp', 'w') as out_fp:
|
||||||
|
for line in in_fp:
|
||||||
|
if line.startswith('['):
|
||||||
|
continue
|
||||||
|
out_fp.write('../' + line)
|
||||||
|
|
||||||
|
os.chdir('po')
|
||||||
|
distutils.spawn.spawn([
|
||||||
|
'xgettext',
|
||||||
|
'--directory=.',
|
||||||
|
'--add-comments',
|
||||||
|
'--from-code=UTF-8',
|
||||||
|
'--keyword=pgettext:1c,2',
|
||||||
|
'--output=subiquity.pot',
|
||||||
|
'--files-from=POTFILES.in.tmp',
|
||||||
|
])
|
||||||
|
os.chdir('..')
|
||||||
|
os.unlink('po/POTFILES.in.tmp')
|
||||||
|
|
||||||
|
for po_file in glob.glob("po/*.po"):
|
||||||
|
lang = os.path.basename(po_file[:-3])
|
||||||
|
mo_dir = os.path.join("build", "mo", lang, "LC_MESSAGES")
|
||||||
|
mo_file = os.path.join(mo_dir, "subiquity.mo")
|
||||||
|
if not os.path.exists(mo_dir):
|
||||||
|
os.makedirs(mo_dir)
|
||||||
|
distutils.spawn.spawn(["msgfmt", po_file, "-o", mo_file])
|
||||||
|
targetpath = os.path.join("share/locale", lang, "LC_MESSAGES")
|
||||||
|
data_files.append((targetpath, (mo_file,)))
|
||||||
|
|
||||||
|
|
||||||
|
class build(distutils.command.build.build):
|
||||||
|
|
||||||
|
sub_commands = distutils.command.build.build.sub_commands + [
|
||||||
|
("build_i18n", None)]
|
||||||
|
|
||||||
|
|
||||||
with open(os.path.join(os.path.dirname(__file__),
|
with open(os.path.join(os.path.dirname(__file__),
|
||||||
|
@ -43,6 +89,7 @@ with open(os.path.join(os.path.dirname(__file__),
|
||||||
exec('\n'.join(lines), ns)
|
exec('\n'.join(lines), ns)
|
||||||
version = ns['__version__']
|
version = ns['__version__']
|
||||||
|
|
||||||
|
|
||||||
if sys.argv[-1] == 'clean':
|
if sys.argv[-1] == 'clean':
|
||||||
print("Cleaning up ...")
|
print("Cleaning up ...")
|
||||||
os.system('rm -rf subiquity.egg-info build dist')
|
os.system('rm -rf subiquity.egg-info build dist')
|
||||||
|
@ -75,4 +122,8 @@ setup(name='subiquity',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
data_files=[],
|
data_files=[],
|
||||||
**setup_kwargs)
|
cmdclass={
|
||||||
|
'build': build,
|
||||||
|
'build_i18n': build_i18n,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
|
@ -68,7 +68,6 @@ parts:
|
||||||
- libsystemd-dev
|
- libsystemd-dev
|
||||||
- lsb-release
|
- lsb-release
|
||||||
- pkg-config
|
- pkg-config
|
||||||
- python3-distutils-extra
|
|
||||||
- python3-urwid
|
- python3-urwid
|
||||||
stage-packages:
|
stage-packages:
|
||||||
- cloud-init
|
- cloud-init
|
||||||
|
@ -76,7 +75,6 @@ parts:
|
||||||
- iso-codes
|
- iso-codes
|
||||||
- lsb-release
|
- lsb-release
|
||||||
- python3-bson
|
- python3-bson
|
||||||
- python3-distutils-extra
|
|
||||||
- python3-urwid
|
- python3-urwid
|
||||||
- python3-requests
|
- python3-requests
|
||||||
- python3-requests-unixsocket
|
- python3-requests-unixsocket
|
||||||
|
|
|
@ -614,10 +614,13 @@ class ZdevInfo:
|
||||||
@property
|
@property
|
||||||
def status(self):
|
def status(self):
|
||||||
if self.failed:
|
if self.failed:
|
||||||
|
# for translator: failed is a zdev device status
|
||||||
return Color.info_error(Text(_("failed"), align="center"))
|
return Color.info_error(Text(_("failed"), align="center"))
|
||||||
if self.auto and self.on:
|
if self.auto and self.on:
|
||||||
|
# for translator: auto is a zdev device status
|
||||||
return Color.info_minor(Text(_("auto"), align="center"))
|
return Color.info_minor(Text(_("auto"), align="center"))
|
||||||
if self.pers and self.on:
|
if self.pers and self.on:
|
||||||
|
# for translator: online is a zdev device status
|
||||||
return Text(_("online"), align="center")
|
return Text(_("online"), align="center")
|
||||||
return Text("", align="center")
|
return Text("", align="center")
|
||||||
|
|
||||||
|
|
|
@ -219,8 +219,8 @@ class Subiquity(Application):
|
||||||
our_tty = "/dev/not a tty"
|
our_tty = "/dev/not a tty"
|
||||||
if not self.interactive() and our_tty != primary_tty:
|
if not self.interactive() and our_tty != primary_tty:
|
||||||
print(
|
print(
|
||||||
_("the installer running on {} will perform the "
|
_("the installer running on {tty} will perform the "
|
||||||
"autoinstall").format(primary_tty))
|
"autoinstall").format(tty=primary_tty))
|
||||||
signal.pause()
|
signal.pause()
|
||||||
self.controllers.load("Reporting")
|
self.controllers.load("Reporting")
|
||||||
self.controllers.Reporting.start()
|
self.controllers.Reporting.start()
|
||||||
|
@ -232,8 +232,8 @@ class Subiquity(Application):
|
||||||
stamp_file = self.state_path("early-commands")
|
stamp_file = self.state_path("early-commands")
|
||||||
if our_tty != primary_tty:
|
if our_tty != primary_tty:
|
||||||
print(
|
print(
|
||||||
_("waiting for installer running on {} to run early "
|
_("waiting for installer running on {tty} to run early "
|
||||||
"commands").format(primary_tty))
|
"commands").format(tty=primary_tty))
|
||||||
while not os.path.exists(stamp_file):
|
while not os.path.exists(stamp_file):
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
elif not os.path.exists(stamp_file):
|
elif not os.path.exists(stamp_file):
|
||||||
|
@ -275,7 +275,7 @@ class Subiquity(Application):
|
||||||
ErrorReportKind.UI, "Installer UI", interrupt=False,
|
ErrorReportKind.UI, "Installer UI", interrupt=False,
|
||||||
wait=True)
|
wait=True)
|
||||||
if report is not None:
|
if report is not None:
|
||||||
print("report saved to {}".format(report.path))
|
print("report saved to {path}".format(path=report.path))
|
||||||
except Exception:
|
except Exception:
|
||||||
print("report generation failed")
|
print("report generation failed")
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
|
|
@ -31,6 +31,9 @@ from curtin.util import human2bytes
|
||||||
|
|
||||||
from probert.storage import StorageInfo
|
from probert.storage import StorageInfo
|
||||||
|
|
||||||
|
from subiquitycore.gettext38 import pgettext
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger('subiquity.models.filesystem')
|
log = logging.getLogger('subiquity.models.filesystem')
|
||||||
|
|
||||||
|
|
||||||
|
@ -145,7 +148,9 @@ class RaidLevel:
|
||||||
|
|
||||||
|
|
||||||
raidlevels = [
|
raidlevels = [
|
||||||
|
# for translators: this is a description of a RAID level
|
||||||
RaidLevel(_("0 (striped)"), "raid0", 2, False),
|
RaidLevel(_("0 (striped)"), "raid0", 2, False),
|
||||||
|
# for translators: this is a description of a RAID level
|
||||||
RaidLevel(_("1 (mirrored)"), "raid1", 2),
|
RaidLevel(_("1 (mirrored)"), "raid1", 2),
|
||||||
RaidLevel(_("5"), "raid5", 3),
|
RaidLevel(_("5"), "raid5", 3),
|
||||||
RaidLevel(_("6"), "raid6", 4),
|
RaidLevel(_("6"), "raid6", 4),
|
||||||
|
@ -183,7 +188,8 @@ def dehumanize_size(size):
|
||||||
size_in = size
|
size_in = size
|
||||||
|
|
||||||
if not size:
|
if not size:
|
||||||
raise ValueError("input cannot be empty")
|
# Attempting to convert input to a size
|
||||||
|
raise ValueError(_("input cannot be empty"))
|
||||||
|
|
||||||
if not size[-1].isdigit():
|
if not size[-1].isdigit():
|
||||||
suffix = size[-1].upper()
|
suffix = size[-1].upper()
|
||||||
|
@ -193,7 +199,9 @@ def dehumanize_size(size):
|
||||||
|
|
||||||
parts = size.split('.')
|
parts = size.split('.')
|
||||||
if len(parts) > 2:
|
if len(parts) > 2:
|
||||||
raise ValueError(_("{!r} is not valid input").format(size_in))
|
raise ValueError(
|
||||||
|
# Attempting to convert input to a size
|
||||||
|
_("{input!r} is not valid input").format(input=size_in))
|
||||||
elif len(parts) == 2:
|
elif len(parts) == 2:
|
||||||
div = 10 ** len(parts[1])
|
div = 10 ** len(parts[1])
|
||||||
size = parts[0] + parts[1]
|
size = parts[0] + parts[1]
|
||||||
|
@ -203,19 +211,23 @@ def dehumanize_size(size):
|
||||||
try:
|
try:
|
||||||
num = int(size)
|
num = int(size)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValueError(_("{!r} is not valid input").format(size_in))
|
raise ValueError(
|
||||||
|
# Attempting to convert input to a size
|
||||||
|
_("{input!r} is not valid input").format(input=size_in))
|
||||||
|
|
||||||
if suffix is not None:
|
if suffix is not None:
|
||||||
if suffix not in HUMAN_UNITS:
|
if suffix not in HUMAN_UNITS:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"unrecognized suffix {!r} in {!r}".format(size_in[-1],
|
# Attempting to convert input to a size
|
||||||
size_in))
|
"unrecognized suffix {suffix!r} in {input!r}".format(
|
||||||
|
suffix=size_in[-1], input=size_in))
|
||||||
mult = 2 ** (10 * HUMAN_UNITS.index(suffix))
|
mult = 2 ** (10 * HUMAN_UNITS.index(suffix))
|
||||||
else:
|
else:
|
||||||
mult = 1
|
mult = 1
|
||||||
|
|
||||||
if num < 0:
|
if num < 0:
|
||||||
raise ValueError("{!r}: cannot be negative".format(size_in))
|
# Attempting to convert input to a size
|
||||||
|
raise ValueError("{input!r}: cannot be negative".format(input=size_in))
|
||||||
|
|
||||||
return num * mult // div
|
return num * mult // div
|
||||||
|
|
||||||
|
@ -401,15 +413,20 @@ def asdict(inst):
|
||||||
|
|
||||||
|
|
||||||
class DeviceAction(enum.Enum):
|
class DeviceAction(enum.Enum):
|
||||||
INFO = _("Info")
|
# Information about a drive
|
||||||
EDIT = _("Edit")
|
INFO = pgettext("DeviceAction", "Info")
|
||||||
REFORMAT = _("Reformat")
|
# Edit a device (partition, logical volume, RAID, etc)
|
||||||
PARTITION = _("Add Partition")
|
EDIT = pgettext("DeviceAction", "Edit")
|
||||||
CREATE_LV = _("Create Logical Volume")
|
REFORMAT = pgettext("DeviceAction", "Reformat")
|
||||||
FORMAT = _("Format")
|
PARTITION = pgettext("DeviceAction", "Add Partition")
|
||||||
REMOVE = _("Remove from RAID/LVM")
|
CREATE_LV = pgettext("DeviceAction", "Create Logical Volume")
|
||||||
DELETE = _("Delete")
|
FORMAT = pgettext("DeviceAction", "Format")
|
||||||
TOGGLE_BOOT = _("Make Boot Device")
|
REMOVE = pgettext("DeviceAction", "Remove from RAID/LVM")
|
||||||
|
DELETE = pgettext("DeviceAction", "Delete")
|
||||||
|
TOGGLE_BOOT = pgettext("DeviceAction", "Make Boot Device")
|
||||||
|
|
||||||
|
def str(self):
|
||||||
|
return pgettext(type(self).__name__, self.value)
|
||||||
|
|
||||||
|
|
||||||
def _generic_can_EDIT(obj):
|
def _generic_can_EDIT(obj):
|
||||||
|
@ -485,8 +502,10 @@ class _Formattable(ABC):
|
||||||
if preserve is None:
|
if preserve is None:
|
||||||
return []
|
return []
|
||||||
elif preserve:
|
elif preserve:
|
||||||
|
# A pre-existing device such as a partition or RAID
|
||||||
return [_("existing")]
|
return [_("existing")]
|
||||||
else:
|
else:
|
||||||
|
# A newly created device such as a partition or RAID
|
||||||
return [_("new")]
|
return [_("new")]
|
||||||
|
|
||||||
# Filesystem
|
# Filesystem
|
||||||
|
@ -515,13 +534,19 @@ class _Formattable(ABC):
|
||||||
if self._m.is_mounted_filesystem(fs.fstype):
|
if self._m.is_mounted_filesystem(fs.fstype):
|
||||||
m = fs.mount()
|
m = fs.mount()
|
||||||
if m:
|
if m:
|
||||||
|
# A filesytem
|
||||||
r.append(_("mounted at {path}").format(path=m.path))
|
r.append(_("mounted at {path}").format(path=m.path))
|
||||||
elif getattr(self, 'flag', None) != "boot":
|
elif getattr(self, 'flag', None) != "boot":
|
||||||
|
# A filesytem
|
||||||
r.append(_("not mounted"))
|
r.append(_("not mounted"))
|
||||||
elif fs.preserve:
|
elif fs.preserve:
|
||||||
if fs.mount() is None:
|
if fs.mount() is None:
|
||||||
|
# A filesytem that cannot be mounted (i.e. swap)
|
||||||
|
# is used or unused
|
||||||
r.append(_("unused"))
|
r.append(_("unused"))
|
||||||
else:
|
else:
|
||||||
|
# A filesytem that cannot be mounted (i.e. swap)
|
||||||
|
# is used or unused
|
||||||
r.append(_("used"))
|
r.append(_("used"))
|
||||||
return r
|
return r
|
||||||
else:
|
else:
|
||||||
|
@ -890,8 +915,10 @@ class Partition(_Formattable):
|
||||||
r.append("PReP")
|
r.append("PReP")
|
||||||
if self.preserve:
|
if self.preserve:
|
||||||
if self.grub_device:
|
if self.grub_device:
|
||||||
|
# boot loader partition
|
||||||
r.append(_("configured"))
|
r.append(_("configured"))
|
||||||
else:
|
else:
|
||||||
|
# boot loader partition
|
||||||
r.append(_("unconfigured"))
|
r.append(_("unconfigured"))
|
||||||
elif self.flag == "boot":
|
elif self.flag == "boot":
|
||||||
if self.fs() and self.fs().mount():
|
if self.fs() and self.fs().mount():
|
||||||
|
@ -908,8 +935,10 @@ class Partition(_Formattable):
|
||||||
r.append(_("unconfigured"))
|
r.append(_("unconfigured"))
|
||||||
r.append("bios_grub")
|
r.append("bios_grub")
|
||||||
elif self.flag == "extended":
|
elif self.flag == "extended":
|
||||||
|
# extended partition
|
||||||
r.append(_("extended"))
|
r.append(_("extended"))
|
||||||
elif self.flag == "logical":
|
elif self.flag == "logical":
|
||||||
|
# logical partition
|
||||||
r.append(_("logical"))
|
r.append(_("logical"))
|
||||||
return r
|
return r
|
||||||
|
|
||||||
|
@ -1085,6 +1114,7 @@ class LVM_VolGroup(_Device):
|
||||||
r = super().annotations
|
r = super().annotations
|
||||||
member = next(iter(self.devices))
|
member = next(iter(self.devices))
|
||||||
if member.type == "dm_crypt":
|
if member.type == "dm_crypt":
|
||||||
|
# Flag for a LVM volume group
|
||||||
r.append(_("encrypted"))
|
r.append(_("encrypted"))
|
||||||
return r
|
return r
|
||||||
|
|
||||||
|
|
|
@ -13,9 +13,9 @@
|
||||||
# You should have received a copy of the GNU Affero General Public License
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import gettext
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from subiquitycore import gettext38
|
||||||
from subiquitycore import i18n
|
from subiquitycore import i18n
|
||||||
|
|
||||||
|
|
||||||
|
@ -53,9 +53,9 @@ class LocaleModel(object):
|
||||||
languages = []
|
languages = []
|
||||||
for code, name in self.supported_languages:
|
for code, name in self.supported_languages:
|
||||||
native = name
|
native = name
|
||||||
if gettext.find('iso_639_3', languages=[code]):
|
if gettext38.find('iso_639_3', languages=[code]):
|
||||||
native_lang = gettext.translation('iso_639_3',
|
native_lang = gettext38.translation('iso_639_3',
|
||||||
languages=[code])
|
languages=[code])
|
||||||
native = native_lang.gettext(name).capitalize()
|
native = native_lang.gettext(name).capitalize()
|
||||||
languages.append((code, native))
|
languages.append((code, native))
|
||||||
return languages
|
return languages
|
||||||
|
|
|
@ -126,13 +126,13 @@ class MultiDeviceChooser(WidgetWrap, WantsToKnowFormField):
|
||||||
def _summarize(self, prefix, device):
|
def _summarize(self, prefix, device):
|
||||||
if device.fs() is not None:
|
if device.fs() is not None:
|
||||||
fs = device.fs()
|
fs = device.fs()
|
||||||
text = prefix + _("formatted as {}").format(fs.fstype)
|
text = prefix + _("formatted as {fstype}").format(fstype=fs.fstype)
|
||||||
if fs.mount():
|
if fs.mount():
|
||||||
text += _(", mounted at {}").format(fs.mount().path)
|
text += _(", mounted at {path}").format(path=fs.mount().path)
|
||||||
else:
|
else:
|
||||||
text += _(", not mounted")
|
text += _(", not mounted")
|
||||||
else:
|
else:
|
||||||
text = prefix + _("unused {}").format(device.desc())
|
text = prefix + _("unused {device}").format(device=device.desc())
|
||||||
return TableRow([(2, Color.info_minor(Text(text)))])
|
return TableRow([(2, Color.info_minor(Text(text)))])
|
||||||
|
|
||||||
def set_bound_form_field(self, bff):
|
def set_bound_form_field(self, bff):
|
||||||
|
|
|
@ -13,10 +13,10 @@
|
||||||
# You should have received a copy of the GNU Affero General Public License
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
from gettext import ngettext
|
|
||||||
import logging
|
import logging
|
||||||
from urwid import Text
|
from urwid import Text
|
||||||
|
|
||||||
|
from subiquitycore.gettext38 import ngettext
|
||||||
from subiquitycore.ui.buttons import danger_btn, other_btn
|
from subiquitycore.ui.buttons import danger_btn, other_btn
|
||||||
from subiquitycore.ui.table import (
|
from subiquitycore.ui.table import (
|
||||||
TablePile,
|
TablePile,
|
||||||
|
@ -60,13 +60,13 @@ class ConfirmDeleteStretchy(Stretchy):
|
||||||
n = len(obj.partitions())
|
n = len(obj.partitions())
|
||||||
if obj.type == "lvm_volgroup":
|
if obj.type == "lvm_volgroup":
|
||||||
line = ngettext(
|
line = ngettext(
|
||||||
_("It contains 1 logical volume"),
|
"It contains 1 logical volume",
|
||||||
_("It contains {n} logical volumes"),
|
"It contains {n} logical volumes",
|
||||||
n)
|
n)
|
||||||
else:
|
else:
|
||||||
line = ngettext(
|
line = ngettext(
|
||||||
_("It contains 1 partition"),
|
"It contains 1 partition",
|
||||||
_("It contains {n} partitions"),
|
"It contains {n} partitions",
|
||||||
n)
|
n)
|
||||||
lines.append(Text(line.format(n=n)))
|
lines.append(Text(line.format(n=n)))
|
||||||
lines.append(Text(""))
|
lines.append(Text(""))
|
||||||
|
@ -106,12 +106,14 @@ class ConfirmReformatStretchy(Stretchy):
|
||||||
|
|
||||||
fs = obj.fs()
|
fs = obj.fs()
|
||||||
if fs is not None:
|
if fs is not None:
|
||||||
title = _("Remove filesystem from {}").format(obj.desc())
|
title = _(
|
||||||
|
"Remove filesystem from {device}"
|
||||||
|
).format(device=obj.desc())
|
||||||
lines = [
|
lines = [
|
||||||
_(
|
_(
|
||||||
"Do you really want to remove the existing filesystem "
|
"Do you really want to remove the existing filesystem "
|
||||||
"from {}?"
|
"from {device}?"
|
||||||
).format(obj.label),
|
).format(device=obj.label),
|
||||||
"",
|
"",
|
||||||
]
|
]
|
||||||
m = fs.mount()
|
m = fs.mount()
|
||||||
|
@ -130,6 +132,7 @@ class ConfirmReformatStretchy(Stretchy):
|
||||||
things = _("logical volumes")
|
things = _("logical volumes")
|
||||||
else:
|
else:
|
||||||
things = _("partitions")
|
things = _("partitions")
|
||||||
|
# things is either "logical volumes" or "partitions"
|
||||||
title = _("Remove all {things} from {obj}").format(
|
title = _("Remove all {things} from {obj}").format(
|
||||||
things=things, obj=obj.desc())
|
things=things, obj=obj.desc())
|
||||||
lines = [
|
lines = [
|
||||||
|
|
|
@ -52,7 +52,7 @@ class DiskInfoStretchy(Stretchy):
|
||||||
Text(""),
|
Text(""),
|
||||||
button_pile([done_btn(_("Close"), on_press=self.close)]),
|
button_pile([done_btn(_("Close"), on_press=self.close)]),
|
||||||
]
|
]
|
||||||
title = _("Info for {}").format(disk.label)
|
title = _("Info for {device}").format(device=disk.label)
|
||||||
super().__init__(title, widgets, 0, 2)
|
super().__init__(title, widgets, 0, 2)
|
||||||
|
|
||||||
def close(self, button=None):
|
def close(self, button=None):
|
||||||
|
|
|
@ -319,7 +319,7 @@ class DeviceList(WidgetWrap):
|
||||||
if cd:
|
if cd:
|
||||||
return _("Remove from {device}").format(device=cd.desc())
|
return _("Remove from {device}").format(device=cd.desc())
|
||||||
else:
|
else:
|
||||||
return _(action.value)
|
return action.str()
|
||||||
|
|
||||||
def _label_PARTITION(self, action, device):
|
def _label_PARTITION(self, action, device):
|
||||||
return _("Add {ptype} Partition").format(
|
return _("Add {ptype} Partition").format(
|
||||||
|
@ -339,7 +339,7 @@ class DeviceList(WidgetWrap):
|
||||||
device_actions = []
|
device_actions = []
|
||||||
for action in device.supported_actions:
|
for action in device.supported_actions:
|
||||||
label_meth = getattr(
|
label_meth = getattr(
|
||||||
self, '_label_{}'.format(action.name), lambda a, d: _(a.value))
|
self, '_label_{}'.format(action.name), lambda a, d: a.str())
|
||||||
label = label_meth(action, device)
|
label = label_meth(action, device)
|
||||||
enabled, whynot = device.action_possible(action)
|
enabled, whynot = device.action_possible(action)
|
||||||
if whynot:
|
if whynot:
|
||||||
|
|
|
@ -81,7 +81,7 @@ class VolGroupForm(CompoundDiskForm):
|
||||||
self.vg_names = vg_names
|
self.vg_names = vg_names
|
||||||
super().__init__(model, possible_components, initial)
|
super().__init__(model, possible_components, initial)
|
||||||
connect_signal(self.encrypt.widget, 'change', self._change_encrypt)
|
connect_signal(self.encrypt.widget, 'change', self._change_encrypt)
|
||||||
setup_password_validation(self, _("Passphrases"))
|
setup_password_validation(self, _("passphrases"))
|
||||||
self._change_encrypt(None, self.encrypt.value)
|
self._change_encrypt(None, self.encrypt.value)
|
||||||
|
|
||||||
name = VGNameField(_("Name:"))
|
name = VGNameField(_("Name:"))
|
||||||
|
|
|
@ -232,16 +232,21 @@ class PartitionForm(Form):
|
||||||
if v.startswith('-'):
|
if v.startswith('-'):
|
||||||
return _("The name of a logical volume cannot start with a hyphen")
|
return _("The name of a logical volume cannot start with a hyphen")
|
||||||
if v in ('.', '..', 'snapshot', 'pvmove'):
|
if v in ('.', '..', 'snapshot', 'pvmove'):
|
||||||
return _("A logical volume may not be called {}").format(v)
|
return _(
|
||||||
|
"A logical volume may not be called {name}"
|
||||||
|
).format(name=v)
|
||||||
for substring in ['_cdata', '_cmeta', '_corig', '_mlog', '_mimage',
|
for substring in ['_cdata', '_cmeta', '_corig', '_mlog', '_mimage',
|
||||||
'_pmspare', '_rimage', '_rmeta', '_tdata',
|
'_pmspare', '_rimage', '_rmeta', '_tdata',
|
||||||
'_tmeta', '_vorigin']:
|
'_tmeta', '_vorigin']:
|
||||||
if substring in v:
|
if substring in v:
|
||||||
return _('The name of a logical volume may not contain '
|
return _(
|
||||||
'"{}"').format(substring)
|
'The name of a logical volume may not contain '
|
||||||
|
'"{substring}"'
|
||||||
|
).format(substring=substring)
|
||||||
if v in self.lvm_names:
|
if v in self.lvm_names:
|
||||||
return _("There is already a logical volume named {}.").format(
|
return _(
|
||||||
self.name.value)
|
"There is already a logical volume named {name}."
|
||||||
|
).format(name=self.name.value)
|
||||||
|
|
||||||
def validate_mount(self):
|
def validate_mount(self):
|
||||||
mount = self.mount.value
|
mount = self.mount.value
|
||||||
|
@ -583,7 +588,7 @@ class FormatEntireStretchy(Stretchy):
|
||||||
self.form.buttons,
|
self.form.buttons,
|
||||||
]
|
]
|
||||||
|
|
||||||
title = _("Format and/or mount {}").format(device.label)
|
title = _("Format and/or mount {device}").format(device=device.label)
|
||||||
|
|
||||||
super().__init__(title, widgets, 0, 0)
|
super().__init__(title, widgets, 0, 0)
|
||||||
|
|
||||||
|
|
|
@ -101,8 +101,8 @@ class RaidForm(CompoundDiskForm):
|
||||||
|
|
||||||
def validate_name(self):
|
def validate_name(self):
|
||||||
if self.name.value in self.raid_names:
|
if self.name.value in self.raid_names:
|
||||||
return _("There is already a RAID named '{}'").format(
|
return _("There is already a RAID named '{name}'").format(
|
||||||
self.name.value)
|
name=self.name.value)
|
||||||
if self.name.value in ('/dev/md/.', '/dev/md/..'):
|
if self.name.value in ('/dev/md/.', '/dev/md/..'):
|
||||||
return _(". and .. are not valid names for RAID devices")
|
return _(". and .. are not valid names for RAID devices")
|
||||||
|
|
||||||
|
|
|
@ -91,15 +91,18 @@ class IdentityForm(Form):
|
||||||
|
|
||||||
def validate_realname(self):
|
def validate_realname(self):
|
||||||
if len(self.realname.value) > REALNAME_MAXLEN:
|
if len(self.realname.value) > REALNAME_MAXLEN:
|
||||||
return _("Realname too long, must be < ") + str(REALNAME_MAXLEN)
|
return _(
|
||||||
|
"Name too long, must be less than {limit}"
|
||||||
|
).format(limit=REALNAME_MAXLEN)
|
||||||
|
|
||||||
def validate_hostname(self):
|
def validate_hostname(self):
|
||||||
if len(self.hostname.value) < 1:
|
if len(self.hostname.value) < 1:
|
||||||
return _("Server name must not be empty")
|
return _("Server name must not be empty")
|
||||||
|
|
||||||
if len(self.hostname.value) > HOSTNAME_MAXLEN:
|
if len(self.hostname.value) > HOSTNAME_MAXLEN:
|
||||||
return (_("Server name too long, must be < ") +
|
return _(
|
||||||
str(HOSTNAME_MAXLEN))
|
"Server name too long, must be less than {limit}"
|
||||||
|
).format(limit=HOSTNAME_MAXLEN)
|
||||||
|
|
||||||
if not re.match(r'[a-z_][a-z0-9_-]*', self.hostname.value):
|
if not re.match(r'[a-z_][a-z0-9_-]*', self.hostname.value):
|
||||||
return _("Hostname must match NAME_REGEX, i.e. [a-z_][a-z0-9_-]*")
|
return _("Hostname must match NAME_REGEX, i.e. [a-z_][a-z0-9_-]*")
|
||||||
|
@ -110,7 +113,9 @@ class IdentityForm(Form):
|
||||||
return _("Username missing")
|
return _("Username missing")
|
||||||
|
|
||||||
if len(username) > USERNAME_MAXLEN:
|
if len(username) > USERNAME_MAXLEN:
|
||||||
return _("Username too long, must be < ") + str(USERNAME_MAXLEN)
|
return _(
|
||||||
|
"Username too long, must be less than {limit}"
|
||||||
|
).format(limit=USERNAME_MAXLEN)
|
||||||
|
|
||||||
if not re.match(r'[a-z_][a-z0-9_-]*', username):
|
if not re.match(r'[a-z_][a-z0-9_-]*', username):
|
||||||
return _("Username must match NAME_REGEX, i.e. [a-z_][a-z0-9_-]*")
|
return _("Username must match NAME_REGEX, i.e. [a-z_][a-z0-9_-]*")
|
||||||
|
@ -134,6 +139,7 @@ def setup_password_validation(form, desc):
|
||||||
password = form.password.value
|
password = form.password.value
|
||||||
if not password.startswith(new_text):
|
if not password.startswith(new_text):
|
||||||
form.confirm_password.show_extra(
|
form.confirm_password.show_extra(
|
||||||
|
# desc is "passwords" or "passphrases"
|
||||||
("info_error", _("{desc} do not match").format(desc=desc)))
|
("info_error", _("{desc} do not match").format(desc=desc)))
|
||||||
else:
|
else:
|
||||||
form.confirm_password.show_extra('')
|
form.confirm_password.show_extra('')
|
||||||
|
|
|
@ -253,7 +253,7 @@ class InstallRunning(Stretchy):
|
||||||
button_pile([self.btn]),
|
button_pile([self.btn]),
|
||||||
]
|
]
|
||||||
super().__init__(
|
super().__init__(
|
||||||
_(""),
|
"",
|
||||||
widgets,
|
widgets,
|
||||||
stretchy_index=0,
|
stretchy_index=0,
|
||||||
focus_index=2)
|
focus_index=2)
|
||||||
|
|
|
@ -253,7 +253,7 @@ class FetchingInfo(WidgetWrap):
|
||||||
self.spinner = Spinner(aio_loop, style='dots')
|
self.spinner = Spinner(aio_loop, style='dots')
|
||||||
self.spinner.start()
|
self.spinner.start()
|
||||||
self.closed = False
|
self.closed = False
|
||||||
text = _("Fetching info for {}").format(snap.name)
|
text = _("Fetching info for {snap}").format(snap=snap.name)
|
||||||
# | text |
|
# | text |
|
||||||
# 12 34
|
# 12 34
|
||||||
self.width = len(text) + 4
|
self.width = len(text) + 4
|
||||||
|
@ -279,7 +279,7 @@ class FetchingFailed(WidgetWrap):
|
||||||
def __init__(self, row, snap):
|
def __init__(self, row, snap):
|
||||||
self.row = row
|
self.row = row
|
||||||
self.closed = False
|
self.closed = False
|
||||||
text = _("Fetching info for {} failed").format(snap.name)
|
text = _("Fetching info for {snap} failed").format(snap=snap.name)
|
||||||
# | text |
|
# | text |
|
||||||
# 12 34
|
# 12 34
|
||||||
self.width = len(text) + 4
|
self.width = len(text) + 4
|
||||||
|
|
|
@ -0,0 +1,797 @@
|
||||||
|
"""Internationalization and localization support.
|
||||||
|
|
||||||
|
This module provides internationalization (I18N) and localization (L10N)
|
||||||
|
support for your Python programs by providing an interface to the GNU gettext
|
||||||
|
message catalog library.
|
||||||
|
|
||||||
|
I18N refers to the operation by which a program is made aware of multiple
|
||||||
|
languages. L10N refers to the adaptation of your program, once
|
||||||
|
internationalized, to the local language and cultural habits.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
# This module represents the integration of work, contributions, feedback, and
|
||||||
|
# suggestions from the following people:
|
||||||
|
#
|
||||||
|
# Martin von Loewis, who wrote the initial implementation of the underlying
|
||||||
|
# C-based libintlmodule (later renamed _gettext), along with a skeletal
|
||||||
|
# gettext.py implementation.
|
||||||
|
#
|
||||||
|
# Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
|
||||||
|
# which also included a pure-Python implementation to read .mo files if
|
||||||
|
# intlmodule wasn't available.
|
||||||
|
#
|
||||||
|
# James Henstridge, who also wrote a gettext.py module, which has some
|
||||||
|
# interesting, but currently unsupported experimental features: the notion of
|
||||||
|
# a Catalog class and instances, and the ability to add to a catalog file via
|
||||||
|
# a Python API.
|
||||||
|
#
|
||||||
|
# Barry Warsaw integrated these modules, wrote the .install() API and code,
|
||||||
|
# and conformed all C and Python code to Python's coding standards.
|
||||||
|
#
|
||||||
|
# Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
|
||||||
|
# module.
|
||||||
|
#
|
||||||
|
# J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
|
||||||
|
#
|
||||||
|
# TODO:
|
||||||
|
# - Lazy loading of .mo files. Currently the entire catalog is loaded into
|
||||||
|
# memory, but that's probably bad for large translated programs. Instead,
|
||||||
|
# the lexical sort of original strings in GNU .mo files should be exploited
|
||||||
|
# to do binary searches and lazy initializations. Or you might want to use
|
||||||
|
# the undocumented double-hash algorithm for .mo files with hash tables, but
|
||||||
|
# you'll need to study the GNU gettext code to do this.
|
||||||
|
#
|
||||||
|
# - Support Solaris .mo file formats. Unfortunately, we've been unable to
|
||||||
|
# find this format documented anywhere.
|
||||||
|
|
||||||
|
|
||||||
|
import locale
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
|
||||||
|
'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
|
||||||
|
'bind_textdomain_codeset',
|
||||||
|
'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
|
||||||
|
'ldngettext', 'lngettext', 'ngettext',
|
||||||
|
'pgettext', 'dpgettext', 'npgettext', 'dnpgettext',
|
||||||
|
]
|
||||||
|
|
||||||
|
_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
|
||||||
|
|
||||||
|
# Expression parsing for plural form selection.
|
||||||
|
#
|
||||||
|
# The gettext library supports a small subset of C syntax. The only
|
||||||
|
# incompatible difference is that integer literals starting with zero are
|
||||||
|
# decimal.
|
||||||
|
#
|
||||||
|
# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
|
||||||
|
# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
|
||||||
|
|
||||||
|
_token_pattern = re.compile(r"""
|
||||||
|
(?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
|
||||||
|
(?P<NUMBER>[0-9]+\b) | # decimal integer
|
||||||
|
(?P<NAME>n\b) | # only n is allowed
|
||||||
|
(?P<PARENTHESIS>[()]) |
|
||||||
|
(?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
|
||||||
|
# <=, >=, ==, !=, &&, ||,
|
||||||
|
# ? :
|
||||||
|
# unary and bitwise ops
|
||||||
|
# not allowed
|
||||||
|
(?P<INVALID>\w+|.) # invalid token
|
||||||
|
""", re.VERBOSE|re.DOTALL)
|
||||||
|
|
||||||
|
def _tokenize(plural):
|
||||||
|
for mo in re.finditer(_token_pattern, plural):
|
||||||
|
kind = mo.lastgroup
|
||||||
|
if kind == 'WHITESPACES':
|
||||||
|
continue
|
||||||
|
value = mo.group(kind)
|
||||||
|
if kind == 'INVALID':
|
||||||
|
raise ValueError('invalid token in plural form: %s' % value)
|
||||||
|
yield value
|
||||||
|
yield ''
|
||||||
|
|
||||||
|
def _error(value):
|
||||||
|
if value:
|
||||||
|
return ValueError('unexpected token in plural form: %s' % value)
|
||||||
|
else:
|
||||||
|
return ValueError('unexpected end of plural form')
|
||||||
|
|
||||||
|
_binary_ops = (
|
||||||
|
('||',),
|
||||||
|
('&&',),
|
||||||
|
('==', '!='),
|
||||||
|
('<', '>', '<=', '>='),
|
||||||
|
('+', '-'),
|
||||||
|
('*', '/', '%'),
|
||||||
|
)
|
||||||
|
_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
|
||||||
|
_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
|
||||||
|
|
||||||
|
def _parse(tokens, priority=-1):
|
||||||
|
result = ''
|
||||||
|
nexttok = next(tokens)
|
||||||
|
while nexttok == '!':
|
||||||
|
result += 'not '
|
||||||
|
nexttok = next(tokens)
|
||||||
|
|
||||||
|
if nexttok == '(':
|
||||||
|
sub, nexttok = _parse(tokens)
|
||||||
|
result = '%s(%s)' % (result, sub)
|
||||||
|
if nexttok != ')':
|
||||||
|
raise ValueError('unbalanced parenthesis in plural form')
|
||||||
|
elif nexttok == 'n':
|
||||||
|
result = '%s%s' % (result, nexttok)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
value = int(nexttok, 10)
|
||||||
|
except ValueError:
|
||||||
|
raise _error(nexttok) from None
|
||||||
|
result = '%s%d' % (result, value)
|
||||||
|
nexttok = next(tokens)
|
||||||
|
|
||||||
|
j = 100
|
||||||
|
while nexttok in _binary_ops:
|
||||||
|
i = _binary_ops[nexttok]
|
||||||
|
if i < priority:
|
||||||
|
break
|
||||||
|
# Break chained comparisons
|
||||||
|
if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
|
||||||
|
result = '(%s)' % result
|
||||||
|
# Replace some C operators by their Python equivalents
|
||||||
|
op = _c2py_ops.get(nexttok, nexttok)
|
||||||
|
right, nexttok = _parse(tokens, i + 1)
|
||||||
|
result = '%s %s %s' % (result, op, right)
|
||||||
|
j = i
|
||||||
|
if j == priority == 4: # '<', '>', '<=', '>='
|
||||||
|
result = '(%s)' % result
|
||||||
|
|
||||||
|
if nexttok == '?' and priority <= 0:
|
||||||
|
if_true, nexttok = _parse(tokens, 0)
|
||||||
|
if nexttok != ':':
|
||||||
|
raise _error(nexttok)
|
||||||
|
if_false, nexttok = _parse(tokens)
|
||||||
|
result = '%s if %s else %s' % (if_true, result, if_false)
|
||||||
|
if priority == 0:
|
||||||
|
result = '(%s)' % result
|
||||||
|
|
||||||
|
return result, nexttok
|
||||||
|
|
||||||
|
def _as_int(n):
|
||||||
|
try:
|
||||||
|
i = round(n)
|
||||||
|
except TypeError:
|
||||||
|
raise TypeError('Plural value must be an integer, got %s' %
|
||||||
|
(n.__class__.__name__,)) from None
|
||||||
|
import warnings
|
||||||
|
warnings.warn('Plural value must be an integer, got %s' %
|
||||||
|
(n.__class__.__name__,),
|
||||||
|
DeprecationWarning, 4)
|
||||||
|
return n
|
||||||
|
|
||||||
|
def c2py(plural):
|
||||||
|
"""Gets a C expression as used in PO files for plural forms and returns a
|
||||||
|
Python function that implements an equivalent expression.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if len(plural) > 1000:
|
||||||
|
raise ValueError('plural form expression is too long')
|
||||||
|
try:
|
||||||
|
result, nexttok = _parse(_tokenize(plural))
|
||||||
|
if nexttok:
|
||||||
|
raise _error(nexttok)
|
||||||
|
|
||||||
|
depth = 0
|
||||||
|
for c in result:
|
||||||
|
if c == '(':
|
||||||
|
depth += 1
|
||||||
|
if depth > 20:
|
||||||
|
# Python compiler limit is about 90.
|
||||||
|
# The most complex example has 2.
|
||||||
|
raise ValueError('plural form expression is too complex')
|
||||||
|
elif c == ')':
|
||||||
|
depth -= 1
|
||||||
|
|
||||||
|
ns = {'_as_int': _as_int}
|
||||||
|
exec('''if True:
|
||||||
|
def func(n):
|
||||||
|
if not isinstance(n, int):
|
||||||
|
n = _as_int(n)
|
||||||
|
return int(%s)
|
||||||
|
''' % result, ns)
|
||||||
|
return ns['func']
|
||||||
|
except RecursionError:
|
||||||
|
# Recursion error can be raised in _parse() or exec().
|
||||||
|
raise ValueError('plural form expression is too complex')
|
||||||
|
|
||||||
|
|
||||||
|
def _expand_lang(loc):
|
||||||
|
loc = locale.normalize(loc)
|
||||||
|
COMPONENT_CODESET = 1 << 0
|
||||||
|
COMPONENT_TERRITORY = 1 << 1
|
||||||
|
COMPONENT_MODIFIER = 1 << 2
|
||||||
|
# split up the locale into its base components
|
||||||
|
mask = 0
|
||||||
|
pos = loc.find('@')
|
||||||
|
if pos >= 0:
|
||||||
|
modifier = loc[pos:]
|
||||||
|
loc = loc[:pos]
|
||||||
|
mask |= COMPONENT_MODIFIER
|
||||||
|
else:
|
||||||
|
modifier = ''
|
||||||
|
pos = loc.find('.')
|
||||||
|
if pos >= 0:
|
||||||
|
codeset = loc[pos:]
|
||||||
|
loc = loc[:pos]
|
||||||
|
mask |= COMPONENT_CODESET
|
||||||
|
else:
|
||||||
|
codeset = ''
|
||||||
|
pos = loc.find('_')
|
||||||
|
if pos >= 0:
|
||||||
|
territory = loc[pos:]
|
||||||
|
loc = loc[:pos]
|
||||||
|
mask |= COMPONENT_TERRITORY
|
||||||
|
else:
|
||||||
|
territory = ''
|
||||||
|
language = loc
|
||||||
|
ret = []
|
||||||
|
for i in range(mask+1):
|
||||||
|
if not (i & ~mask): # if all components for this combo exist ...
|
||||||
|
val = language
|
||||||
|
if i & COMPONENT_TERRITORY: val += territory
|
||||||
|
if i & COMPONENT_CODESET: val += codeset
|
||||||
|
if i & COMPONENT_MODIFIER: val += modifier
|
||||||
|
ret.append(val)
|
||||||
|
ret.reverse()
|
||||||
|
return ret
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class NullTranslations:
|
||||||
|
def __init__(self, fp=None):
|
||||||
|
self._info = {}
|
||||||
|
self._charset = None
|
||||||
|
self._output_charset = None
|
||||||
|
self._fallback = None
|
||||||
|
if fp is not None:
|
||||||
|
self._parse(fp)
|
||||||
|
|
||||||
|
def _parse(self, fp):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def add_fallback(self, fallback):
|
||||||
|
if self._fallback:
|
||||||
|
self._fallback.add_fallback(fallback)
|
||||||
|
else:
|
||||||
|
self._fallback = fallback
|
||||||
|
|
||||||
|
def gettext(self, message):
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.gettext(message)
|
||||||
|
return message
|
||||||
|
|
||||||
|
def lgettext(self, message):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('lgettext() is deprecated, use gettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
if self._fallback:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
return self._fallback.lgettext(message)
|
||||||
|
if self._output_charset:
|
||||||
|
return message.encode(self._output_charset)
|
||||||
|
return message.encode(locale.getpreferredencoding())
|
||||||
|
|
||||||
|
def ngettext(self, msgid1, msgid2, n):
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.ngettext(msgid1, msgid2, n)
|
||||||
|
if n == 1:
|
||||||
|
return msgid1
|
||||||
|
else:
|
||||||
|
return msgid2
|
||||||
|
|
||||||
|
def lngettext(self, msgid1, msgid2, n):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('lngettext() is deprecated, use ngettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
if self._fallback:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
return self._fallback.lngettext(msgid1, msgid2, n)
|
||||||
|
if n == 1:
|
||||||
|
tmsg = msgid1
|
||||||
|
else:
|
||||||
|
tmsg = msgid2
|
||||||
|
if self._output_charset:
|
||||||
|
return tmsg.encode(self._output_charset)
|
||||||
|
return tmsg.encode(locale.getpreferredencoding())
|
||||||
|
|
||||||
|
def pgettext(self, context, message):
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.pgettext(context, message)
|
||||||
|
return message
|
||||||
|
|
||||||
|
def npgettext(self, context, msgid1, msgid2, n):
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.npgettext(context, msgid1, msgid2, n)
|
||||||
|
if n == 1:
|
||||||
|
return msgid1
|
||||||
|
else:
|
||||||
|
return msgid2
|
||||||
|
|
||||||
|
def info(self):
|
||||||
|
return self._info
|
||||||
|
|
||||||
|
def charset(self):
|
||||||
|
return self._charset
|
||||||
|
|
||||||
|
def output_charset(self):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('output_charset() is deprecated',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
return self._output_charset
|
||||||
|
|
||||||
|
def set_output_charset(self, charset):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('set_output_charset() is deprecated',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
self._output_charset = charset
|
||||||
|
|
||||||
|
def install(self, names=None):
|
||||||
|
import builtins
|
||||||
|
builtins.__dict__['_'] = self.gettext
|
||||||
|
if names is not None:
|
||||||
|
allowed = {'gettext', 'lgettext', 'lngettext',
|
||||||
|
'ngettext', 'npgettext', 'pgettext'}
|
||||||
|
for name in allowed & set(names):
|
||||||
|
builtins.__dict__[name] = getattr(self, name)
|
||||||
|
|
||||||
|
|
||||||
|
class GNUTranslations(NullTranslations):
|
||||||
|
# Magic number of .mo files
|
||||||
|
LE_MAGIC = 0x950412de
|
||||||
|
BE_MAGIC = 0xde120495
|
||||||
|
|
||||||
|
# The encoding of a msgctxt and a msgid in a .mo file is
|
||||||
|
# msgctxt + "\x04" + msgid (gettext version >= 0.15)
|
||||||
|
CONTEXT = "%s\x04%s"
|
||||||
|
|
||||||
|
# Acceptable .mo versions
|
||||||
|
VERSIONS = (0, 1)
|
||||||
|
|
||||||
|
def _get_versions(self, version):
|
||||||
|
"""Returns a tuple of major version, minor version"""
|
||||||
|
return (version >> 16, version & 0xffff)
|
||||||
|
|
||||||
|
def _parse(self, fp):
|
||||||
|
"""Override this method to support alternative .mo formats."""
|
||||||
|
# Delay struct import for speeding up gettext import when .mo files
|
||||||
|
# are not used.
|
||||||
|
from struct import unpack
|
||||||
|
filename = getattr(fp, 'name', '')
|
||||||
|
# Parse the .mo file header, which consists of 5 little endian 32
|
||||||
|
# bit words.
|
||||||
|
self._catalog = catalog = {}
|
||||||
|
self.plural = lambda n: int(n != 1) # germanic plural by default
|
||||||
|
buf = fp.read()
|
||||||
|
buflen = len(buf)
|
||||||
|
# Are we big endian or little endian?
|
||||||
|
magic = unpack('<I', buf[:4])[0]
|
||||||
|
if magic == self.LE_MAGIC:
|
||||||
|
version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
|
||||||
|
ii = '<II'
|
||||||
|
elif magic == self.BE_MAGIC:
|
||||||
|
version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
|
||||||
|
ii = '>II'
|
||||||
|
else:
|
||||||
|
raise OSError(0, 'Bad magic number', filename)
|
||||||
|
|
||||||
|
major_version, minor_version = self._get_versions(version)
|
||||||
|
|
||||||
|
if major_version not in self.VERSIONS:
|
||||||
|
raise OSError(0, 'Bad version number ' + str(major_version), filename)
|
||||||
|
|
||||||
|
# Now put all messages from the .mo file buffer into the catalog
|
||||||
|
# dictionary.
|
||||||
|
for i in range(0, msgcount):
|
||||||
|
mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
|
||||||
|
mend = moff + mlen
|
||||||
|
tlen, toff = unpack(ii, buf[transidx:transidx+8])
|
||||||
|
tend = toff + tlen
|
||||||
|
if mend < buflen and tend < buflen:
|
||||||
|
msg = buf[moff:mend]
|
||||||
|
tmsg = buf[toff:tend]
|
||||||
|
else:
|
||||||
|
raise OSError(0, 'File is corrupt', filename)
|
||||||
|
# See if we're looking at GNU .mo conventions for metadata
|
||||||
|
if mlen == 0:
|
||||||
|
# Catalog description
|
||||||
|
lastk = None
|
||||||
|
for b_item in tmsg.split(b'\n'):
|
||||||
|
item = b_item.decode().strip()
|
||||||
|
if not item:
|
||||||
|
continue
|
||||||
|
# Skip over comment lines:
|
||||||
|
if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
|
||||||
|
continue
|
||||||
|
k = v = None
|
||||||
|
if ':' in item:
|
||||||
|
k, v = item.split(':', 1)
|
||||||
|
k = k.strip().lower()
|
||||||
|
v = v.strip()
|
||||||
|
self._info[k] = v
|
||||||
|
lastk = k
|
||||||
|
elif lastk:
|
||||||
|
self._info[lastk] += '\n' + item
|
||||||
|
if k == 'content-type':
|
||||||
|
self._charset = v.split('charset=')[1]
|
||||||
|
elif k == 'plural-forms':
|
||||||
|
v = v.split(';')
|
||||||
|
plural = v[1].split('plural=')[1]
|
||||||
|
self.plural = c2py(plural)
|
||||||
|
# Note: we unconditionally convert both msgids and msgstrs to
|
||||||
|
# Unicode using the character encoding specified in the charset
|
||||||
|
# parameter of the Content-Type header. The gettext documentation
|
||||||
|
# strongly encourages msgids to be us-ascii, but some applications
|
||||||
|
# require alternative encodings (e.g. Zope's ZCML and ZPT). For
|
||||||
|
# traditional gettext applications, the msgid conversion will
|
||||||
|
# cause no problems since us-ascii should always be a subset of
|
||||||
|
# the charset encoding. We may want to fall back to 8-bit msgids
|
||||||
|
# if the Unicode conversion fails.
|
||||||
|
charset = self._charset or 'ascii'
|
||||||
|
if b'\x00' in msg:
|
||||||
|
# Plural forms
|
||||||
|
msgid1, msgid2 = msg.split(b'\x00')
|
||||||
|
tmsg = tmsg.split(b'\x00')
|
||||||
|
msgid1 = str(msgid1, charset)
|
||||||
|
for i, x in enumerate(tmsg):
|
||||||
|
catalog[(msgid1, i)] = str(x, charset)
|
||||||
|
else:
|
||||||
|
catalog[str(msg, charset)] = str(tmsg, charset)
|
||||||
|
# advance to next entry in the seek tables
|
||||||
|
masteridx += 8
|
||||||
|
transidx += 8
|
||||||
|
|
||||||
|
def lgettext(self, message):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('lgettext() is deprecated, use gettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
missing = object()
|
||||||
|
tmsg = self._catalog.get(message, missing)
|
||||||
|
if tmsg is missing:
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.lgettext(message)
|
||||||
|
tmsg = message
|
||||||
|
if self._output_charset:
|
||||||
|
return tmsg.encode(self._output_charset)
|
||||||
|
return tmsg.encode(locale.getpreferredencoding())
|
||||||
|
|
||||||
|
def lngettext(self, msgid1, msgid2, n):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('lngettext() is deprecated, use ngettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
try:
|
||||||
|
tmsg = self._catalog[(msgid1, self.plural(n))]
|
||||||
|
except KeyError:
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.lngettext(msgid1, msgid2, n)
|
||||||
|
if n == 1:
|
||||||
|
tmsg = msgid1
|
||||||
|
else:
|
||||||
|
tmsg = msgid2
|
||||||
|
if self._output_charset:
|
||||||
|
return tmsg.encode(self._output_charset)
|
||||||
|
return tmsg.encode(locale.getpreferredencoding())
|
||||||
|
|
||||||
|
def gettext(self, message):
|
||||||
|
missing = object()
|
||||||
|
tmsg = self._catalog.get(message, missing)
|
||||||
|
if tmsg is missing:
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.gettext(message)
|
||||||
|
return message
|
||||||
|
return tmsg
|
||||||
|
|
||||||
|
def ngettext(self, msgid1, msgid2, n):
|
||||||
|
try:
|
||||||
|
tmsg = self._catalog[(msgid1, self.plural(n))]
|
||||||
|
except KeyError:
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.ngettext(msgid1, msgid2, n)
|
||||||
|
if n == 1:
|
||||||
|
tmsg = msgid1
|
||||||
|
else:
|
||||||
|
tmsg = msgid2
|
||||||
|
return tmsg
|
||||||
|
|
||||||
|
def pgettext(self, context, message):
|
||||||
|
ctxt_msg_id = self.CONTEXT % (context, message)
|
||||||
|
missing = object()
|
||||||
|
tmsg = self._catalog.get(ctxt_msg_id, missing)
|
||||||
|
if tmsg is missing:
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.pgettext(context, message)
|
||||||
|
return message
|
||||||
|
return tmsg
|
||||||
|
|
||||||
|
def npgettext(self, context, msgid1, msgid2, n):
|
||||||
|
ctxt_msg_id = self.CONTEXT % (context, msgid1)
|
||||||
|
try:
|
||||||
|
tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
|
||||||
|
except KeyError:
|
||||||
|
if self._fallback:
|
||||||
|
return self._fallback.npgettext(context, msgid1, msgid2, n)
|
||||||
|
if n == 1:
|
||||||
|
tmsg = msgid1
|
||||||
|
else:
|
||||||
|
tmsg = msgid2
|
||||||
|
return tmsg
|
||||||
|
|
||||||
|
|
||||||
|
# Locate a .mo file using the gettext strategy
|
||||||
|
def find(domain, localedir=None, languages=None, all=False):
|
||||||
|
# Get some reasonable defaults for arguments that were not supplied
|
||||||
|
if localedir is None:
|
||||||
|
localedir = _default_localedir
|
||||||
|
if languages is None:
|
||||||
|
languages = []
|
||||||
|
for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
|
||||||
|
val = os.environ.get(envar)
|
||||||
|
if val:
|
||||||
|
languages = val.split(':')
|
||||||
|
break
|
||||||
|
if 'C' not in languages:
|
||||||
|
languages.append('C')
|
||||||
|
# now normalize and expand the languages
|
||||||
|
nelangs = []
|
||||||
|
for lang in languages:
|
||||||
|
for nelang in _expand_lang(lang):
|
||||||
|
if nelang not in nelangs:
|
||||||
|
nelangs.append(nelang)
|
||||||
|
# select a language
|
||||||
|
if all:
|
||||||
|
result = []
|
||||||
|
else:
|
||||||
|
result = None
|
||||||
|
for lang in nelangs:
|
||||||
|
if lang == 'C':
|
||||||
|
break
|
||||||
|
mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
|
||||||
|
mofile_lp = os.path.join("/usr/share/locale-langpack", lang,
|
||||||
|
'LC_MESSAGES', '%s.mo' % domain)
|
||||||
|
|
||||||
|
# first look into the standard locale dir, then into the
|
||||||
|
# langpack locale dir
|
||||||
|
|
||||||
|
# standard mo file
|
||||||
|
if os.path.exists(mofile):
|
||||||
|
if all:
|
||||||
|
result.append(mofile)
|
||||||
|
else:
|
||||||
|
return mofile
|
||||||
|
|
||||||
|
# langpack mofile -> use it
|
||||||
|
if os.path.exists(mofile_lp):
|
||||||
|
if all:
|
||||||
|
result.append(mofile_lp)
|
||||||
|
else:
|
||||||
|
return mofile_lp
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# a mapping between absolute .mo file path and Translation object
|
||||||
|
_translations = {}
|
||||||
|
_unspecified = ['unspecified']
|
||||||
|
|
||||||
|
def translation(domain, localedir=None, languages=None,
|
||||||
|
class_=None, fallback=False, codeset=_unspecified):
|
||||||
|
if class_ is None:
|
||||||
|
class_ = GNUTranslations
|
||||||
|
mofiles = find(domain, localedir, languages, all=True)
|
||||||
|
if not mofiles:
|
||||||
|
if fallback:
|
||||||
|
return NullTranslations()
|
||||||
|
from errno import ENOENT
|
||||||
|
raise FileNotFoundError(ENOENT,
|
||||||
|
'No translation file found for domain', domain)
|
||||||
|
# Avoid opening, reading, and parsing the .mo file after it's been done
|
||||||
|
# once.
|
||||||
|
result = None
|
||||||
|
for mofile in mofiles:
|
||||||
|
key = (class_, os.path.abspath(mofile))
|
||||||
|
t = _translations.get(key)
|
||||||
|
if t is None:
|
||||||
|
with open(mofile, 'rb') as fp:
|
||||||
|
t = _translations.setdefault(key, class_(fp))
|
||||||
|
# Copy the translation object to allow setting fallbacks and
|
||||||
|
# output charset. All other instance data is shared with the
|
||||||
|
# cached object.
|
||||||
|
# Delay copy import for speeding up gettext import when .mo files
|
||||||
|
# are not used.
|
||||||
|
import copy
|
||||||
|
t = copy.copy(t)
|
||||||
|
if codeset is not _unspecified:
|
||||||
|
import warnings
|
||||||
|
warnings.warn('parameter codeset is deprecated',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
if codeset:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\bset_output_charset\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
t.set_output_charset(codeset)
|
||||||
|
if result is None:
|
||||||
|
result = t
|
||||||
|
else:
|
||||||
|
result.add_fallback(t)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def install(domain, localedir=None, codeset=_unspecified, names=None):
|
||||||
|
t = translation(domain, localedir, fallback=True, codeset=codeset)
|
||||||
|
t.install(names)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# a mapping b/w domains and locale directories
|
||||||
|
_localedirs = {}
|
||||||
|
# a mapping b/w domains and codesets
|
||||||
|
_localecodesets = {}
|
||||||
|
# current global domain, `messages' used for compatibility w/ GNU gettext
|
||||||
|
_current_domain = 'messages'
|
||||||
|
|
||||||
|
|
||||||
|
def textdomain(domain=None):
|
||||||
|
global _current_domain
|
||||||
|
if domain is not None:
|
||||||
|
_current_domain = domain
|
||||||
|
return _current_domain
|
||||||
|
|
||||||
|
|
||||||
|
def bindtextdomain(domain, localedir=None):
|
||||||
|
global _localedirs
|
||||||
|
if localedir is not None:
|
||||||
|
_localedirs[domain] = localedir
|
||||||
|
return _localedirs.get(domain, _default_localedir)
|
||||||
|
|
||||||
|
|
||||||
|
def bind_textdomain_codeset(domain, codeset=None):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('bind_textdomain_codeset() is deprecated',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
global _localecodesets
|
||||||
|
if codeset is not None:
|
||||||
|
_localecodesets[domain] = codeset
|
||||||
|
return _localecodesets.get(domain)
|
||||||
|
|
||||||
|
|
||||||
|
def dgettext(domain, message):
|
||||||
|
try:
|
||||||
|
t = translation(domain, _localedirs.get(domain, None))
|
||||||
|
except OSError:
|
||||||
|
return message
|
||||||
|
return t.gettext(message)
|
||||||
|
|
||||||
|
def ldgettext(domain, message):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('ldgettext() is deprecated, use dgettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
codeset = _localecodesets.get(domain)
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
|
||||||
|
except OSError:
|
||||||
|
return message.encode(codeset or locale.getpreferredencoding())
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
return t.lgettext(message)
|
||||||
|
|
||||||
|
def dngettext(domain, msgid1, msgid2, n):
|
||||||
|
try:
|
||||||
|
t = translation(domain, _localedirs.get(domain, None))
|
||||||
|
except OSError:
|
||||||
|
if n == 1:
|
||||||
|
return msgid1
|
||||||
|
else:
|
||||||
|
return msgid2
|
||||||
|
return t.ngettext(msgid1, msgid2, n)
|
||||||
|
|
||||||
|
def ldngettext(domain, msgid1, msgid2, n):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('ldngettext() is deprecated, use dngettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
codeset = _localecodesets.get(domain)
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
|
||||||
|
except OSError:
|
||||||
|
if n == 1:
|
||||||
|
tmsg = msgid1
|
||||||
|
else:
|
||||||
|
tmsg = msgid2
|
||||||
|
return tmsg.encode(codeset or locale.getpreferredencoding())
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
return t.lngettext(msgid1, msgid2, n)
|
||||||
|
|
||||||
|
|
||||||
|
def dpgettext(domain, context, message):
|
||||||
|
try:
|
||||||
|
t = translation(domain, _localedirs.get(domain, None))
|
||||||
|
except OSError:
|
||||||
|
return message
|
||||||
|
return t.pgettext(context, message)
|
||||||
|
|
||||||
|
|
||||||
|
def dnpgettext(domain, context, msgid1, msgid2, n):
|
||||||
|
try:
|
||||||
|
t = translation(domain, _localedirs.get(domain, None))
|
||||||
|
except OSError:
|
||||||
|
if n == 1:
|
||||||
|
return msgid1
|
||||||
|
else:
|
||||||
|
return msgid2
|
||||||
|
return t.npgettext(context, msgid1, msgid2, n)
|
||||||
|
|
||||||
|
|
||||||
|
def gettext(message):
|
||||||
|
return dgettext(_current_domain, message)
|
||||||
|
|
||||||
|
def lgettext(message):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('lgettext() is deprecated, use gettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\bldgettext\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
return ldgettext(_current_domain, message)
|
||||||
|
|
||||||
|
def ngettext(msgid1, msgid2, n):
|
||||||
|
return dngettext(_current_domain, msgid1, msgid2, n)
|
||||||
|
|
||||||
|
def lngettext(msgid1, msgid2, n):
|
||||||
|
import warnings
|
||||||
|
warnings.warn('lngettext() is deprecated, use ngettext() instead',
|
||||||
|
DeprecationWarning, 2)
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.filterwarnings('ignore', r'.*\bldngettext\b.*',
|
||||||
|
DeprecationWarning)
|
||||||
|
return ldngettext(_current_domain, msgid1, msgid2, n)
|
||||||
|
|
||||||
|
|
||||||
|
def pgettext(context, message):
|
||||||
|
return dpgettext(_current_domain, context, message)
|
||||||
|
|
||||||
|
|
||||||
|
def npgettext(context, msgid1, msgid2, n):
|
||||||
|
return dnpgettext(_current_domain, context, msgid1, msgid2, n)
|
||||||
|
|
||||||
|
|
||||||
|
# dcgettext() has been deemed unnecessary and is not implemented.
|
||||||
|
|
||||||
|
# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
|
||||||
|
# was:
|
||||||
|
#
|
||||||
|
# import gettext
|
||||||
|
# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
|
||||||
|
# _ = cat.gettext
|
||||||
|
# print _('Hello World')
|
||||||
|
|
||||||
|
# The resulting catalog object currently don't support access through a
|
||||||
|
# dictionary API, which was supported (but apparently unused) in GNOME
|
||||||
|
# gettext.
|
||||||
|
|
||||||
|
Catalog = translation
|
|
@ -14,7 +14,7 @@
|
||||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
|
||||||
import gettext
|
from . import gettext38
|
||||||
import os
|
import os
|
||||||
import syslog
|
import syslog
|
||||||
|
|
||||||
|
@ -38,8 +38,8 @@ def switch_language(code='en_US'):
|
||||||
def my_gettext(message):
|
def my_gettext(message):
|
||||||
return message
|
return message
|
||||||
elif code:
|
elif code:
|
||||||
translation = gettext.translation('subiquity', localedir=localedir,
|
translation = gettext38.translation('subiquity', localedir=localedir,
|
||||||
languages=[code], fallback=True)
|
languages=[code], fallback=True)
|
||||||
|
|
||||||
def my_gettext(message):
|
def my_gettext(message):
|
||||||
if not message:
|
if not message:
|
||||||
|
|
|
@ -19,6 +19,7 @@ import logging
|
||||||
import yaml
|
import yaml
|
||||||
from socket import AF_INET, AF_INET6
|
from socket import AF_INET, AF_INET6
|
||||||
|
|
||||||
|
from subiquitycore.gettext38 import pgettext
|
||||||
from subiquitycore import netplan
|
from subiquitycore import netplan
|
||||||
|
|
||||||
|
|
||||||
|
@ -34,13 +35,17 @@ def addr_version(ip):
|
||||||
|
|
||||||
|
|
||||||
class NetDevAction(enum.Enum):
|
class NetDevAction(enum.Enum):
|
||||||
INFO = _("Info")
|
# Information about a network interface
|
||||||
EDIT_WLAN = _("Edit Wifi")
|
INFO = pgettext("NetDevAction", "Info")
|
||||||
EDIT_IPV4 = _("Edit IPv4")
|
EDIT_WLAN = pgettext("NetDevAction", "Edit Wifi")
|
||||||
EDIT_IPV6 = _("Edit IPv6")
|
EDIT_IPV4 = pgettext("NetDevAction", "Edit IPv4")
|
||||||
EDIT_BOND = _("Edit bond")
|
EDIT_IPV6 = pgettext("NetDevAction", "Edit IPv6")
|
||||||
ADD_VLAN = _("Add a VLAN tag")
|
EDIT_BOND = pgettext("NetDevAction", "Edit bond")
|
||||||
DELETE = _("Delete")
|
ADD_VLAN = pgettext("NetDevAction", "Add a VLAN tag")
|
||||||
|
DELETE = pgettext("NetDevAction", "Delete")
|
||||||
|
|
||||||
|
def str(self):
|
||||||
|
return pgettext(type(self).__name__, self.value)
|
||||||
|
|
||||||
|
|
||||||
class BondParameters:
|
class BondParameters:
|
||||||
|
|
|
@ -367,7 +367,9 @@ class URLEditor(StringEditor, WantsToKnowFormField):
|
||||||
schemes = schemes[0] + _(" or ") + schemes[1]
|
schemes = schemes[0] + _(" or ") + schemes[1]
|
||||||
else:
|
else:
|
||||||
schemes = schemes[0]
|
schemes = schemes[0]
|
||||||
raise ValueError(_("This field must be a %s URL.") % schemes)
|
raise ValueError(
|
||||||
|
_("This field must be a {schemes} URL.").format(
|
||||||
|
schemes=schemes))
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -226,6 +226,7 @@ class NetworkView(BaseView):
|
||||||
addrs.append(str(ip))
|
addrs.append(str(ip))
|
||||||
if addrs:
|
if addrs:
|
||||||
address_info.append(
|
address_info.append(
|
||||||
|
# Network addressing mode (static/dhcp/disabled)
|
||||||
(Text(_('static')), Text(', '.join(addrs))))
|
(Text(_('static')), Text(', '.join(addrs))))
|
||||||
if len(address_info) == 0:
|
if len(address_info) == 0:
|
||||||
# Do not show an interface as disabled if it is part of a bond or
|
# Do not show an interface as disabled if it is part of a bond or
|
||||||
|
@ -234,6 +235,7 @@ class NetworkView(BaseView):
|
||||||
reason = dev.disabled_reason
|
reason = dev.disabled_reason
|
||||||
if reason is None:
|
if reason is None:
|
||||||
reason = ""
|
reason = ""
|
||||||
|
# Network addressing mode (static/dhcp/disabled)
|
||||||
address_info.append((Text(_("disabled")), Text(reason)))
|
address_info.append((Text(_("disabled")), Text(reason)))
|
||||||
rows = []
|
rows = []
|
||||||
for label, value in address_info:
|
for label, value in address_info:
|
||||||
|
@ -333,7 +335,7 @@ class NetworkView(BaseView):
|
||||||
opens_dialog = getattr(meth, 'opens_dialog', False)
|
opens_dialog = getattr(meth, 'opens_dialog', False)
|
||||||
if dev.supports_action(action):
|
if dev.supports_action(action):
|
||||||
actions.append(
|
actions.append(
|
||||||
(_(action.value), True, (action, meth), opens_dialog))
|
(action.str(), True, (action, meth), opens_dialog))
|
||||||
|
|
||||||
menu = ActionMenu(actions)
|
menu = ActionMenu(actions)
|
||||||
connect_signal(menu, 'action', self._action, dev)
|
connect_signal(menu, 'action', self._action, dev)
|
||||||
|
|
|
@ -111,7 +111,9 @@ class NetworkConfigForm(Form):
|
||||||
return
|
return
|
||||||
if address not in subnet:
|
if address not in subnet:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
_("'%s' is not contained in '%s'") % (address, subnet))
|
_("'{address}' is not contained in '{subnet}'").format(
|
||||||
|
address, subnet)
|
||||||
|
)
|
||||||
return address
|
return address
|
||||||
|
|
||||||
def clean_gateway(self, gateway):
|
def clean_gateway(self, gateway):
|
||||||
|
@ -137,8 +139,11 @@ class NetworkConfigForm(Form):
|
||||||
|
|
||||||
|
|
||||||
network_choices = [
|
network_choices = [
|
||||||
|
# A choice for how to configure a network interface
|
||||||
(_("Automatic (DHCP)"), True, "dhcp"),
|
(_("Automatic (DHCP)"), True, "dhcp"),
|
||||||
|
# A choice for how to configure a network interface
|
||||||
(_("Manual"), True, "manual"),
|
(_("Manual"), True, "manual"),
|
||||||
|
# A choice for how to configure a network interface
|
||||||
(_("Disabled"), True, "disable"),
|
(_("Disabled"), True, "disable"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -284,7 +289,7 @@ class VlanForm(Form):
|
||||||
new_name = '%s.%s' % (self.device.name, self.vlan.value)
|
new_name = '%s.%s' % (self.device.name, self.vlan.value)
|
||||||
if new_name in self.parent.model.devices_by_name:
|
if new_name in self.parent.model.devices_by_name:
|
||||||
if self.parent.model.devices_by_name[new_name].config is not None:
|
if self.parent.model.devices_by_name[new_name].config is not None:
|
||||||
return _("%s already exists") % new_name
|
return _("{netdev} already exists").format(netdev=new_name)
|
||||||
|
|
||||||
|
|
||||||
class AddVlanStretchy(Stretchy):
|
class AddVlanStretchy(Stretchy):
|
||||||
|
@ -328,6 +333,7 @@ class ViewInterfaceInfo(Stretchy):
|
||||||
Text(""),
|
Text(""),
|
||||||
button_pile([done_btn(_("Close"), on_press=self.close)]),
|
button_pile([done_btn(_("Close"), on_press=self.close)]),
|
||||||
]
|
]
|
||||||
|
# {device} is the name of a network device
|
||||||
title = _("Info for {device}").format(device=device.name)
|
title = _("Info for {device}").format(device=device.name)
|
||||||
super().__init__(title, widgets, 0, 2)
|
super().__init__(title, widgets, 0, 2)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue