cli.py 4.0 KB

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