From db4450c4cf5bacf0ce678d5f440be0e050811f80 Mon Sep 17 00:00:00 2001 From: Xiaotian Wu Date: Tue, 15 Aug 2023 11:28:48 +0800 Subject: [PATCH] Add functions for CJK string alignment --- archinstall/lib/output.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/archinstall/lib/output.py b/archinstall/lib/output.py index 9f2a2ae31d..0ecdc71b39 100644 --- a/archinstall/lib/output.py +++ b/archinstall/lib/output.py @@ -1,6 +1,7 @@ import logging import os import sys +import unicodedata from enum import Enum from pathlib import Path @@ -326,3 +327,33 @@ def log( if level != logging.DEBUG or storage.get('arguments', {}).get('verbose', False): sys.stdout.write(f"{text}\n") sys.stdout.flush() + +def _count_cjk_chars(string: str) -> int: + "Count the total number of CJK characters contained in a string" + return sum(unicodedata.east_asian_width(c) in 'FW' for c in string) + +def cjk_ljust(string: str, width: int, fillbyte: str = ' ') -> str: + """Return a left-justified CJK string of length width. + >>> cjkljust('Hello', 15, '*') + 'Hello**********' + >>> cjkljust('你好', 15, '*') + '你好***********' + >>> cjkljust('안녕하세요', 15, '*') + '안녕하세요*****' + >>> cjkljust('こんにちは', 15, '*') + 'こんにちは*****' + """ + return string.ljust(width - _count_cjk_chars(string), fillbyte) + +def cjk_rjust(string: str, width: int, fillbyte: str = ' ') -> str: + """Return a right-justified CJK string of length width. + >>> cjkrjust('Hello', 15, '*') + '**********Hello' + >>> cjkrjust('你好', 15, '*') + '***********你好' + >>> cjkrjust('안녕하세요', 15, '*') + '*****안녕하세요' + >>> cjkrjust('こんにちは', 15, '*') + '*****こんにちは' + """ + return string.rjust(width - _count_cjk_chars(string), fillbyte)