cli.py 9.7 KB

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