cli.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import argparse
  2. import logging
  3. import os
  4. import random
  5. import sys
  6. from io import TextIOWrapper
  7. from pathlib import Path
  8. from typing import Dict, List, Optional, TextIO, TypeVar, Union
  9. from . import VERSION, Faker, documentor, exceptions
  10. from .config import AVAILABLE_LOCALES, DEFAULT_LOCALE, META_PROVIDERS_MODULES
  11. from .documentor import Documentor
  12. from .providers import BaseProvider
  13. __author__ = "joke2k"
  14. T = TypeVar("T")
  15. def print_provider(
  16. doc: Documentor,
  17. provider: BaseProvider,
  18. formatters: Dict[str, T],
  19. excludes: Optional[List[str]] = None,
  20. output: Optional[TextIO] = None,
  21. ) -> None:
  22. if output is None:
  23. output = sys.stdout
  24. if excludes is None:
  25. excludes = []
  26. print(file=output)
  27. print(f"### {doc.get_provider_name(provider)}", file=output)
  28. print(file=output)
  29. for signature, example in formatters.items():
  30. if signature in excludes:
  31. continue
  32. try:
  33. lines = str(example).expandtabs().splitlines()
  34. except UnicodeDecodeError:
  35. # The example is actually made of bytes.
  36. # We could coerce to bytes, but that would fail anyway when we wiil
  37. # try to `print` the line.
  38. lines = ["<bytes>"]
  39. except UnicodeEncodeError:
  40. raise Exception(f"error on {signature!r} with value {example!r}")
  41. margin = max(30, doc.max_name_len + 1)
  42. remains = 150 - margin
  43. separator = "#"
  44. for line in lines:
  45. for i in range(0, (len(line) // remains) + 1):
  46. print(
  47. f"\t{signature:<{margin}}{separator} {line[i * remains:(i + 1) * remains]}",
  48. file=output,
  49. )
  50. signature = separator = " "
  51. def print_doc(
  52. provider_or_field: Optional[str] = None,
  53. args: Optional[List[T]] = None,
  54. lang: str = DEFAULT_LOCALE,
  55. output: Optional[Union[TextIO, TextIOWrapper]] = None,
  56. seed: Optional[float] = None,
  57. includes: Optional[List[str]] = None,
  58. ) -> None:
  59. if args is None:
  60. args = []
  61. if output is None:
  62. output = sys.stdout
  63. fake = Faker(locale=lang, includes=includes)
  64. fake.seed_instance(seed)
  65. from faker.providers import BaseProvider
  66. base_provider_formatters = list(dir(BaseProvider))
  67. if provider_or_field:
  68. if "." in provider_or_field:
  69. parts = provider_or_field.split(".")
  70. locale = parts[-2] if parts[-2] in AVAILABLE_LOCALES else lang
  71. fake = Faker(locale, providers=[provider_or_field], includes=includes)
  72. fake.seed_instance(seed)
  73. doc = documentor.Documentor(fake)
  74. doc.already_generated = base_provider_formatters
  75. print_provider(
  76. doc,
  77. fake.get_providers()[0],
  78. doc.get_provider_formatters(fake.get_providers()[0]),
  79. output=output,
  80. )
  81. else:
  82. try:
  83. print(fake.format(provider_or_field, *args), end="", file=output)
  84. except AttributeError:
  85. raise ValueError(f'No faker found for "{provider_or_field}({args})"')
  86. else:
  87. doc = documentor.Documentor(fake)
  88. unsupported: List[str] = []
  89. while True:
  90. try:
  91. formatters = doc.get_formatters(with_args=True, with_defaults=True, excludes=unsupported)
  92. except exceptions.UnsupportedFeature as e:
  93. unsupported.append(e.name)
  94. else:
  95. break
  96. for provider, fakers in formatters:
  97. print_provider(doc, provider, fakers, output=output)
  98. for language in AVAILABLE_LOCALES:
  99. if language == lang:
  100. continue
  101. print(file=output)
  102. print(f"## LANGUAGE {language}", file=output)
  103. fake = Faker(locale=language)
  104. fake.seed_instance(seed)
  105. d = documentor.Documentor(fake)
  106. for p, fs in d.get_formatters(
  107. with_args=True,
  108. with_defaults=True,
  109. locale=language,
  110. excludes=base_provider_formatters + unsupported,
  111. ):
  112. print_provider(d, p, fs, output=output)
  113. class Command:
  114. def __init__(self, argv: Optional[str] = None) -> None:
  115. self.argv = argv or sys.argv[:]
  116. self.prog_name = Path(self.argv[0]).name
  117. def execute(self) -> None:
  118. """
  119. Given the command-line arguments, this creates a parser appropriate
  120. to that command, and runs it.
  121. """
  122. # retrieve default language from system environment
  123. default_locale = os.environ.get("LANG", "en_US").split(".")[0]
  124. if default_locale not in AVAILABLE_LOCALES:
  125. default_locale = DEFAULT_LOCALE
  126. epilog = f"""supported locales:
  127. {', '.join(sorted(AVAILABLE_LOCALES))}
  128. Faker can take a locale as an optional argument, to return localized data. If
  129. no locale argument is specified, the factory falls back to the user's OS
  130. locale as long as it is supported by at least one of the providers.
  131. - for this user, the default locale is {default_locale}.
  132. If the optional argument locale and/or user's default locale is not available
  133. for the specified provider, the factory falls back to faker's default locale,
  134. which is {DEFAULT_LOCALE}.
  135. examples:
  136. $ faker address
  137. 968 Bahringer Garden Apt. 722
  138. Kristinaland, NJ 09890
  139. $ faker -l de_DE address
  140. Samira-Niemeier-Allee 56
  141. 94812 Biedenkopf
  142. $ faker profile ssn,birthdate
  143. {{'ssn': u'628-10-1085', 'birthdate': '2008-03-29'}}
  144. $ faker -r=3 -s=";" name
  145. Willam Kertzmann;
  146. Josiah Maggio;
  147. Gayla Schmitt;
  148. """
  149. formatter_class = argparse.RawDescriptionHelpFormatter
  150. parser = argparse.ArgumentParser(
  151. prog=self.prog_name,
  152. description=f"{self.prog_name} version {VERSION}",
  153. epilog=epilog,
  154. formatter_class=formatter_class,
  155. )
  156. parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
  157. parser.add_argument(
  158. "-v",
  159. "--verbose",
  160. action="store_true",
  161. help="show INFO logging events instead "
  162. "of CRITICAL, which is the default. These logging "
  163. "events provide insight into localization of "
  164. "specific providers.",
  165. )
  166. parser.add_argument(
  167. "-o",
  168. metavar="output",
  169. type=argparse.FileType("w"),
  170. default=sys.stdout,
  171. help="redirect output to a file",
  172. )
  173. parser.add_argument(
  174. "-l",
  175. "--lang",
  176. choices=AVAILABLE_LOCALES,
  177. default=default_locale,
  178. metavar="LOCALE",
  179. help="specify the language for a localized " "provider (e.g. de_DE)",
  180. )
  181. parser.add_argument(
  182. "-r",
  183. "--repeat",
  184. default=1,
  185. type=int,
  186. help="generate the specified number of outputs",
  187. )
  188. parser.add_argument(
  189. "-s",
  190. "--sep",
  191. default="\n",
  192. help="use the specified separator after each " "output",
  193. )
  194. parser.add_argument(
  195. "--seed",
  196. metavar="SEED",
  197. type=int,
  198. help="specify a seed for the random generator so "
  199. "that results are repeatable. Also compatible "
  200. "with 'repeat' option",
  201. )
  202. parser.add_argument(
  203. "-i",
  204. "--include",
  205. default=META_PROVIDERS_MODULES,
  206. nargs="*",
  207. help="list of additional custom providers to "
  208. "user, given as the import path of the module "
  209. "containing your Provider class (not the provider "
  210. "class itself)",
  211. )
  212. parser.add_argument(
  213. "fake",
  214. action="store",
  215. nargs="?",
  216. help="name of the fake to generate output for " "(e.g. profile)",
  217. )
  218. parser.add_argument(
  219. "fake_args",
  220. metavar="fake argument",
  221. action="store",
  222. nargs="*",
  223. help="optional arguments to pass to the fake "
  224. "(e.g. the profile fake takes an optional "
  225. "list of comma separated field names as the "
  226. "first argument)",
  227. )
  228. arguments = parser.parse_args(self.argv[1:])
  229. if arguments.verbose:
  230. logging.basicConfig(level=logging.DEBUG)
  231. else:
  232. logging.basicConfig(level=logging.CRITICAL)
  233. random.seed(arguments.seed)
  234. seeds = [random.random() for _ in range(arguments.repeat)]
  235. for i in range(arguments.repeat):
  236. print_doc(
  237. arguments.fake,
  238. arguments.fake_args,
  239. lang=arguments.lang,
  240. output=arguments.o,
  241. seed=seeds[i],
  242. includes=arguments.include,
  243. )
  244. print(arguments.sep, file=arguments.o)
  245. if not arguments.fake:
  246. # repeat not supported for all docs
  247. break
  248. def execute_from_command_line(argv: Optional[str] = None) -> None:
  249. """A simple method that runs a Command."""
  250. if sys.stdout.encoding is None:
  251. print(
  252. "please set python env PYTHONIOENCODING=UTF-8, example: "
  253. "export PYTHONIOENCODING=UTF-8, when writing to stdout",
  254. file=sys.stderr,
  255. )
  256. exit(1)
  257. command = Command(argv)
  258. command.execute()
  259. if __name__ == "__main__":
  260. execute_from_command_line()