cli.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """Command-line interface for the :mod:`idna` package.
  2. Invoked via ``python -m idna``. See :func:`main` for the entry point.
  3. """
  4. from __future__ import annotations
  5. import argparse
  6. import sys
  7. from itertools import chain
  8. from typing import IO, TYPE_CHECKING
  9. from . import IDNAError, decode, encode, unicode_version
  10. from .core import _alabel_prefix, _unicode_dots_re
  11. from .package_data import __version__
  12. if TYPE_CHECKING:
  13. from collections.abc import Iterable
  14. def _looks_like_alabel(s: str) -> bool:
  15. """Return True if any label in ``s`` carries the ``xn--`` ACE prefix."""
  16. prefix = _alabel_prefix.decode("ascii")
  17. return any(label.lower().startswith(prefix) for label in _unicode_dots_re.split(s))
  18. def _build_parser() -> argparse.ArgumentParser:
  19. parser = argparse.ArgumentParser(
  20. prog="python -m idna",
  21. description=(
  22. "Convert a domain name between its Unicode (U-label) and "
  23. "ASCII-compatible (A-label) forms. With no mode flag, the "
  24. "direction is chosen from the first input — if it contains "
  25. "an xn-- label the stream is decoded, otherwise it is "
  26. "encoded — and the same mode is applied to every remaining "
  27. "input. UTS #46 mapping is applied by default; pass "
  28. "--strict to disable it. When no domains are given on the "
  29. "command line and stdin is piped, one domain per line is "
  30. "read from stdin."
  31. ),
  32. )
  33. mode = parser.add_mutually_exclusive_group()
  34. mode.add_argument(
  35. "-e",
  36. "--encode",
  37. dest="mode",
  38. action="store_const",
  39. const="encode",
  40. help="Encode the input to its ASCII A-label form.",
  41. )
  42. mode.add_argument(
  43. "-d",
  44. "--decode",
  45. dest="mode",
  46. action="store_const",
  47. const="decode",
  48. help="Decode the input from its ASCII A-label form.",
  49. )
  50. parser.add_argument(
  51. "--strict",
  52. action="store_true",
  53. help="Disable the default UTS #46 mapping and apply IDNA 2008 rules verbatim.",
  54. )
  55. parser.add_argument(
  56. "--version",
  57. action="version",
  58. version=f"idna {__version__} (Unicode {unicode_version})",
  59. )
  60. parser.add_argument(
  61. "domain",
  62. nargs="*",
  63. help="One or more domain names to convert. Omit to read from stdin.",
  64. )
  65. return parser
  66. def _iter_stdin(stream: IO[str]) -> Iterable[str]:
  67. """Yield non-empty stripped lines from ``stream``, ignoring blanks."""
  68. for line in stream:
  69. stripped = line.strip()
  70. if stripped:
  71. yield stripped
  72. def _convert_one(domain: str, mode: str, uts46: bool) -> bool:
  73. """Convert ``domain`` and write the result; return ``False`` on failure."""
  74. try:
  75. if mode == "decode":
  76. print(decode(domain, uts46=uts46))
  77. else:
  78. print(encode(domain, uts46=uts46).decode("ascii"))
  79. except IDNAError as err:
  80. print(f"idna: {mode} failed for {domain!r}: {err}", file=sys.stderr)
  81. return False
  82. return True
  83. def main(argv: list[str] | None = None) -> int:
  84. """Entry point for ``python -m idna``.
  85. When more than one domain is supplied (via positional arguments or
  86. piped stdin) and no mode flag is given, the first input determines
  87. the direction and that mode is applied uniformly to the rest.
  88. :param argv: Argument list excluding the program name. Defaults to
  89. :data:`sys.argv` when ``None``.
  90. :returns: ``0`` on success, ``1`` if any conversion fails.
  91. """
  92. parser = _build_parser()
  93. args = parser.parse_args(argv)
  94. uts46 = not args.strict
  95. if args.domain:
  96. domains: Iterable[str] = args.domain
  97. elif not sys.stdin.isatty():
  98. domains = _iter_stdin(sys.stdin)
  99. else:
  100. parser.error("a domain argument is required when stdin is a terminal")
  101. iterator = iter(domains)
  102. first = next(iterator, None)
  103. if first is None:
  104. return 0
  105. mode = args.mode or ("decode" if _looks_like_alabel(first) else "encode")
  106. results = [_convert_one(domain, mode, uts46) for domain in chain([first], iterator)]
  107. return 0 if all(results) else 1
  108. if __name__ == "__main__":
  109. sys.exit(main())