Debian Codegraph @

idna/cli.py

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