Skip to content

Commit

Permalink
add: i18n
Browse files Browse the repository at this point in the history
  • Loading branch information
starsareintherose committed May 23, 2023
1 parent 9964f5e commit c79eb86
Show file tree
Hide file tree
Showing 13 changed files with 932 additions and 53 deletions.
21 changes: 13 additions & 8 deletions lilac
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ from structlog.types import Processor

topdir = Path(__file__).resolve().parent

import gettext
trans = gettext.translation('lilac', localedir='po', languages=['zh_CN'])
_ = trans.gettext

from lilac2.vendor.myutils import lock_file
from lilac2.vendor.serializer import PickledData
from lilac2.vendor.nicelogger import enable_pretty_logging
Expand All @@ -48,6 +52,7 @@ from lilac2.nomypy import BuildResult, BuildReason # type: ignore
from lilac2 import pkgbuild
from lilac2.building import build_package, MissingDependencies
from lilac2 import slogconf
from lilac2 import _
try:
from lilac2 import db
except ImportError:
Expand Down Expand Up @@ -134,8 +139,8 @@ def packages_with_depends(
for name, deps in nonexistent.items():
repo.send_error_report(
repo.lilacinfos[name],
subject='软件包 %s lilac.yaml 指定了不存在的依赖',
msg = f'软件包 {name}lilac.yaml 指定了 repo_depends,然而其直接或者间接的依赖项 {deps!r} 并不在本仓库中。'
subject=_('The dependency of package %s listed in lilac.yaml is missing'),
msg = _('The package {name}\'s lilac.yaml mentions a dependency on {deps!r}, but this repository does not contain the direct or indirect dependency {deps!r} .')
)

sorter = graphlib.TopologicalSorter(dep_building_map)
Expand Down Expand Up @@ -338,7 +343,7 @@ def try_pick_some(
logger.exception('check_update_on_build')
mod = repo.lilacinfos[pkg]
repo.send_error_report(
mod, subject='%s update_on_build 检查出错', exc=e,
mod, subject=_('%s update_on_build check faces error'), exc=e,
)
continue

Expand Down Expand Up @@ -426,10 +431,10 @@ def build_it(
# e.deps - faileddeps = failed previously
failed[pkg] = tuple(e.deps)
if e.deps == faileddeps:
msg = f'{pkg} 的依赖 {faileddeps} 打包失败了。'
msg = _('The packaging of {pkg} failed due to a failed dependency, {faileddeps}.')
else:
msg = f'{pkg} 缺少依赖 {e.deps},其中 {faileddeps} 本次打包失败了。'
repo.send_error_report(mod, subject='%s 出现依赖问题', msg = msg)
msg = _('{pkg} miss dependency {e.deps}, where {faileddeps} failed to package this time.')
repo.send_error_report(mod, subject=_('%s face dependency problems'), msg = msg)
else:
repo.send_error_report(mod, exc=e, logfile=logfile)

Expand Down Expand Up @@ -665,8 +670,8 @@ def main(logdir: Path, pkgs_from_args: List[str]) -> None:
except Exception:
tb = traceback.format_exc()
logger.exception('unexpected error')
subject = '运行时错误'
msg = '调用栈如下\n\n' + tb
subject = _('Error while running')
msg = _('Call stack(s) are following:\n\n') + tb
REPO.report_error(subject, msg)

def setup() -> Path:
Expand Down
2 changes: 1 addition & 1 deletion lilac2/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def update_aur_repo() -> None:
_G.repo.send_error_report(
_G.mod,
exc = e,
subject = '提交软件包 %s AUR 时出错',
subject = _('Pushing package %s to AUR faces error'),
)

def git_pkgbuild_commit() -> None:
Expand Down
4 changes: 2 additions & 2 deletions lilac2/building.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ def build_package(
if staging:
notify_maintainers(
repo, lilacinfo,
f'{pkgbase} {pkg_version} 刚刚打包了',
'软件包已被置于 staging 目录,请查验后手动发布。',
_('{pkgbase} {pkg_version} is just packaged'),
_('The package has been placed in the staging directory, please manually check it before publishing it.'),
)
result = BuildResult.staged()
else:
Expand Down
2 changes: 1 addition & 1 deletion lilac2/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def child_exited(signum: int, sigframe: Optional[types.FrameType]) -> None:
outs = outs.replace('\r\n', '\n')
outs = re.sub(r'.*\r', '', outs)
if outlen > 1024 ** 3: # larger than 1G
outs += '\n\n输出过多,已击杀。\n'
outs += _('\n\nOutput is quite long, already kiled\n')
if code != 0:
# set output by keyword to avoid being included in repr()
raise subprocess.CalledProcessError(code, cmd, output=outs)
Expand Down
2 changes: 1 addition & 1 deletion lilac2/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def sendmail(self, to: Union[str, List[str]],

s = self.smtp_connect()
if len(msg) > 5 * 1024 ** 2:
msg = msg[:1024 ** 2] + '\n\n日志过长,省略ing……\n\n' + \
msg = msg[:1024 ** 2] + _('\n\nLog is quite long and omitted.\n\n') + \
msg[-1024 ** 2:]
mail = assemble_mail('[%s] %s' % (
self.mailtag, subject), to, self.from_, text=msg)
Expand Down
6 changes: 3 additions & 3 deletions lilac2/nvchecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,12 +180,12 @@ def packages_need_update(
for who, their_errors in error_owners.items():
logger.warning('send nvchecker report for %r packages to %s',
{x['name'] for x in their_errors}, who)
repo.sendmail(who, 'nvchecker 错误报告',
repo.sendmail(who, _('nvchecker error report'),
'\n'.join(_format_error(e) for e in their_errors))

if None in errors: # errors belong to unknown packages
subject = 'nvchecker 问题'
msg = '在更新检查时出现了一些错误\n\n' + '\n'.join(
subject = _('nvchecker problem')
msg = _('Face some errors while checking updates\n\n') + '\n'.join(
_format_error(e) for e in errors[None]) + '\n'
repo.send_repo_mail(subject, msg)

Expand Down
36 changes: 18 additions & 18 deletions lilac2/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(self, config: dict[str, Any]) -> None:
@lru_cache()
def maintainer_from_github(self, username: str) -> Optional[Maintainer]:
if self.gh is None:
raise ValueError('未设置 github token,无法从 GitHub 取得用户 Email 地址')
raise ValueError(_('github token is not configured, can\'t get user\'s Email address from GitHub'))

userinfo = self.gh.get_user_info(username)
if userinfo['email']:
Expand All @@ -86,15 +86,15 @@ def parse_maintainers(
try:
u = self.maintainer_from_github(m['github'])
except Exception as e:
errors.append(f'从 GitHub 获取用户 Email 地址时出错{e!r}')
errors.append(_('Face error while getting user\'s Email address from GitHub:{e!r}'))
else:
if u is None:
errors.append(f'GitHub 用户 {m["github"]} 未公开 Email 地址')
errors.append(_('There is no public Email address belonging to GitHub user {m["github"]}'))
else:
ret.append(u)
else:
logger.error('unsupported maintainer info: %r', m)
errors.append(f'不支持的格式{m!r}')
errors.append(_('unsupported format:{m!r}'))
continue

return ret, errors
Expand Down Expand Up @@ -192,8 +192,8 @@ def _find_maintainers_impl(
error_str = '\n'.join(errors)
self.sendmail(
git_maintainer,
subject = f'{pkgbase}maintainers 信息有误',
msg = f"以下 maintainers 信息有误,请修正。\n\n{error_str}\n",
subject = _('{pkgbase}\'s maintainers info error'),
msg = _("The folloing info of maintainers is error, please check and correct them.\n\n{error_str}\n"),
)

if not ret and fallback_git:
Expand Down Expand Up @@ -265,21 +265,21 @@ def send_error_report(
if exc is not None:
tb = ''.join(traceback.format_exception(type(exc), exc, exc.__traceback__))
if isinstance(exc, subprocess.CalledProcessError):
subject_real = subject or '在打包软件包 %s 时发生错误'
msgs.append('命令执行失败\n\n命令 %r 返回了错误号 %d。' % (
subject_real = subject or _('Face error while packaging %s')
msgs.append(_('CMD face error\n\ncommand %r return singal %d。') % (
exc.cmd, exc.returncode))
if exc.output:
msgs.append('命令的输出如下\n\n%s' % exc.output)
msgs.append('调用栈如下\n\n' + tb)
msgs.append(_('Outpur of command\n\n%s') % exc.output)
msgs.append(_('Call stack(s) are following\n\n') + tb)
elif isinstance(exc, api.AurDownloadError):
subject_real = subject or '在获取AUR包 %s 时发生错误'
msgs.append('获取AUR包失败!\n\n')
msgs.append('调用栈如下:\n\n' + tb)
subject_real = subject or _('Error while pulling package %s from AUR')
msgs.append(_('Pulling AUR package failed\n\n'))
msgs.append(_('Call stack(s) are following:\n\n') + tb)
elif isinstance(exc, TimeoutError):
subject_real = subject or '打包软件包 %s 超时'
subject_real = subject or _('Packaging pkg %s timeout')
else:
subject_real = subject or '在打包软件包 %s 时发生未知错误'
msgs.append('发生未知错误!调用栈如下\n\n' + tb)
subject_real = subject or _('Face unknown error while packaging %s')
msgs.append(_('Unknown error occurs, call stack(s) are following\n\n') + tb)
else:
if subject is None:
raise ValueError('subject should be given but not')
Expand All @@ -295,7 +295,7 @@ def send_error_report(
with logfile.open(errors='replace') as f:
build_output = f.read()
if build_output:
log_header = '打包日志:'
log_header = _('Packaging Log:')
with suppress(ValueError, KeyError): # invalid template or wrong key
if self.logurl_template and len(logfile.parts) >= 2:
# assume the directory name is the time stamp for now.
Expand Down Expand Up @@ -338,7 +338,7 @@ def load_managed_lilac_and_report(self) -> dict[str, tuple[str, ...]]:
if not isinstance(exc, Exception):
raise
self.send_error_report(name, exc=exc,
subject='为软件包 %s 载入 lilac.py 时失败')
subject=_('Loading lilac.py for package %s face error'))
build_logger_old.error('%s failed', name)
build_logger.exception('lilac.py error', pkgbase = name, exc_info=exc_info)

Expand Down
4 changes: 2 additions & 2 deletions lilac2/vendor/myutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def getchar(
end: str = '\n',
timeout: Optional[float] = None,
):
'''读取一个字符'''
_('''Read a character''')
import termios
sys.stdout.write(prompt)
sys.stdout.flush()
Expand Down Expand Up @@ -155,7 +155,7 @@ def _read() -> Optional[str]:
return ch

def loadso(fname):
'''ctypes.CDLL 的 wrapper,从 sys.path 中搜索文件'''
_('''wrapper of ctypes.CDLL, searching file(s) from sys.path''')
from ctypes import CDLL

for d in sys.path:
Expand Down
23 changes: 12 additions & 11 deletions lilac2/vendor/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@

class Serializer(metaclass=abc.ABCMeta):
def __init__(self, fname, readonly=False, default=None):
'''
读取文件fname。readonly指定析构时不回存数据
如果数据已加锁,将会抛出SerializerError异常
default 指出如果文件不存在或为空时的数据
注意:
要正确地写回数据,需要保证此对象在需要写回时依旧存在,或者使用with语句
将自身存入其data属性中不可行,原因未知
'''
_('''
Reading file fname.
readonly specifies that the data will not be stored back when it is destructed
If the data is locked, a SerializerError exception will be occur
default indicates the data if the file does not exist or is empty
Notice:
To write back data correctly, you need to ensure that the object still exists when it needs to be written back or use the `with` statement
Storing itself into its data attribute is not feasible considering unknown reasons
''')
self.fname = os.path.abspath(fname)
if readonly:
self.lock = None
Expand All @@ -38,7 +39,7 @@ def __init__(self, fname, readonly=False, default=None):
break
else:
self.lock = None
raise SerializerError('数据已加锁')
raise SerializerError(_('Data is locked'))
with open(self.lock, 'w') as f:
f.write(str(os.getpid()))

Expand All @@ -53,7 +54,7 @@ def __init__(self, fname, readonly=False, default=None):
raise

def __del__(self):
'''如果需要,删除 lock,保存文件'''
_('''If it\'s needed, delete lock,save file(s)''')
if self.lock:
self.save()
os.unlink(self.lock)
Expand Down
12 changes: 6 additions & 6 deletions lilac2/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def run_build_cmd(cmd: Cmd) -> None:
st = os.stat(1)
if st.st_size > 1024 ** 3: # larger than 1G
kill_child_processes()
logger.error('\n\n输出过多,已击杀。')
logger.error(_('\n\nOutput is quite long and killed.'))
else:
if code != 0:
raise subprocess.CalledProcessError(code, cmd)
Expand Down Expand Up @@ -258,17 +258,17 @@ def handle_failure(
if isinstance(e, pkgbuild.ConflictWithOfficialError):
reason = ''
if e.groups:
reason += f'软件包被加入了官方组:{e.groups}\n'
reason += _('Package is added to officail repository: {e.groups}\n')
if e.packages:
reason += f'软件包将取代官方包:{e.packages}\n'
reason += _('Package will replace package in offical repository: {e.packages}\n')
repo.send_error_report(
mod, subject='%s 与官方软件库冲突', msg = reason,
mod, subject=_('%s is conflicted with offical repository'), msg = reason,
)

elif isinstance(e, pkgbuild.DowngradingError):
repo.send_error_report(
mod, subject='%s 新打的包比仓库里的包旧',
msg=f'包 {e.pkgname} 打的版本为 {e.built_version},但在仓库里已有较新版本 {e.repo_version}\n',
mod, subject=_('%s is older than packaged version in this repository'),
msg=_('Current packaging version of package {e.pkgname} is {e.built_version}, however, already newer version {e.repo_version} in repository\n'),
)

else:
Expand Down
Loading

0 comments on commit c79eb86

Please sign in to comment.