__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. """
  2. Standalone file utils.
  3. Nothing in this module should have an knowledge of config or the layout
  4. and structure of the site and pages in the site.
  5. """
  6. import logging
  7. import os
  8. import pkg_resources
  9. import shutil
  10. import re
  11. import yaml
  12. import fnmatch
  13. import posixpath
  14. from datetime import datetime, timezone
  15. from urllib.parse import urlparse
  16. from mkdocs import exceptions
  17. log = logging.getLogger(__name__)
  18. markdown_extensions = [
  19. '.markdown',
  20. '.mdown',
  21. '.mkdn',
  22. '.mkd',
  23. '.md'
  24. ]
  25. def yaml_load(source, loader=yaml.Loader):
  26. """
  27. Wrap PyYaml's loader so we can extend it to suit our needs.
  28. Load all strings as unicode.
  29. https://stackoverflow.com/a/2967461/3609487
  30. """
  31. def construct_yaml_str(self, node):
  32. """
  33. Override the default string handling function to always return
  34. unicode objects.
  35. """
  36. return self.construct_scalar(node)
  37. class Loader(loader):
  38. """
  39. Define a custom loader derived from the global loader to leave the
  40. global loader unaltered.
  41. """
  42. # Attach our unicode constructor to our custom loader ensuring all strings
  43. # will be unicode on translation.
  44. Loader.add_constructor('tag:yaml.org,2002:str', construct_yaml_str)
  45. try:
  46. return yaml.load(source, Loader)
  47. finally:
  48. # TODO: Remove this when external calls are properly cleaning up file
  49. # objects. Some mkdocs internal calls, sometimes in test lib, will
  50. # load configs with a file object but never close it. On some
  51. # systems, if a delete action is performed on that file without Python
  52. # closing that object, there will be an access error. This will
  53. # process the file and close it as there should be no more use for the
  54. # file once we process the yaml content.
  55. if hasattr(source, 'close'):
  56. source.close()
  57. def modified_time(file_path):
  58. """
  59. Return the modified time of the supplied file. If the file does not exists zero is returned.
  60. see build_pages for use.
  61. """
  62. if os.path.exists(file_path):
  63. return os.path.getmtime(file_path)
  64. else:
  65. return 0.0
  66. def get_build_timestamp():
  67. """
  68. Returns the number of seconds since the epoch.
  69. Support SOURCE_DATE_EPOCH environment variable for reproducible builds.
  70. See https://reproducible-builds.org/specs/source-date-epoch/
  71. """
  72. source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
  73. if source_date_epoch is None:
  74. return int(datetime.now(timezone.utc).timestamp())
  75. return int(source_date_epoch)
  76. def get_build_datetime():
  77. """
  78. Returns an aware datetime object.
  79. Support SOURCE_DATE_EPOCH environment variable for reproducible builds.
  80. See https://reproducible-builds.org/specs/source-date-epoch/
  81. """
  82. source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
  83. if source_date_epoch is None:
  84. return datetime.now(timezone.utc)
  85. return datetime.fromtimestamp(int(source_date_epoch), timezone.utc)
  86. def get_build_date():
  87. """
  88. Returns the displayable date string.
  89. Support SOURCE_DATE_EPOCH environment variable for reproducible builds.
  90. See https://reproducible-builds.org/specs/source-date-epoch/
  91. """
  92. return get_build_datetime().strftime('%Y-%m-%d')
  93. def reduce_list(data_set):
  94. """ Reduce duplicate items in a list and preserve order """
  95. seen = set()
  96. return [item for item in data_set if
  97. item not in seen and not seen.add(item)]
  98. def copy_file(source_path, output_path):
  99. """
  100. Copy source_path to output_path, making sure any parent directories exist.
  101. The output_path may be a directory.
  102. """
  103. output_dir = os.path.dirname(output_path)
  104. if not os.path.exists(output_dir):
  105. os.makedirs(output_dir)
  106. if os.path.isdir(output_path):
  107. output_path = os.path.join(output_path, os.path.basename(source_path))
  108. shutil.copyfile(source_path, output_path)
  109. def write_file(content, output_path):
  110. """
  111. Write content to output_path, making sure any parent directories exist.
  112. """
  113. output_dir = os.path.dirname(output_path)
  114. if not os.path.exists(output_dir):
  115. os.makedirs(output_dir)
  116. with open(output_path, 'wb') as f:
  117. f.write(content)
  118. def clean_directory(directory):
  119. """
  120. Remove the content of a directory recursively but not the directory itself.
  121. """
  122. if not os.path.exists(directory):
  123. return
  124. for entry in os.listdir(directory):
  125. # Don't remove hidden files from the directory. We never copy files
  126. # that are hidden, so we shouldn't delete them either.
  127. if entry.startswith('.'):
  128. continue
  129. path = os.path.join(directory, entry)
  130. if os.path.isdir(path):
  131. shutil.rmtree(path, True)
  132. else:
  133. os.unlink(path)
  134. def get_html_path(path):
  135. """
  136. Map a source file path to an output html path.
  137. Paths like 'index.md' will be converted to 'index.html'
  138. Paths like 'about.md' will be converted to 'about/index.html'
  139. Paths like 'api-guide/core.md' will be converted to 'api-guide/core/index.html'
  140. """
  141. path = os.path.splitext(path)[0]
  142. if os.path.basename(path) == 'index':
  143. return path + '.html'
  144. return "/".join((path, 'index.html'))
  145. def get_url_path(path, use_directory_urls=True):
  146. """
  147. Map a source file path to an output html path.
  148. Paths like 'index.md' will be converted to '/'
  149. Paths like 'about.md' will be converted to '/about/'
  150. Paths like 'api-guide/core.md' will be converted to '/api-guide/core/'
  151. If `use_directory_urls` is `False`, returned URLs will include the a trailing
  152. `index.html` rather than just returning the directory path.
  153. """
  154. path = get_html_path(path)
  155. url = '/' + path.replace(os.path.sep, '/')
  156. if use_directory_urls:
  157. return url[:-len('index.html')]
  158. return url
  159. def is_markdown_file(path):
  160. """
  161. Return True if the given file path is a Markdown file.
  162. https://superuser.com/questions/249436/file-extension-for-markdown-files
  163. """
  164. return any(fnmatch.fnmatch(path.lower(), '*{}'.format(x)) for x in markdown_extensions)
  165. def is_html_file(path):
  166. """
  167. Return True if the given file path is an HTML file.
  168. """
  169. ext = os.path.splitext(path)[1].lower()
  170. return ext in [
  171. '.html',
  172. '.htm',
  173. ]
  174. def is_template_file(path):
  175. """
  176. Return True if the given file path is an HTML file.
  177. """
  178. ext = os.path.splitext(path)[1].lower()
  179. return ext in [
  180. '.html',
  181. '.htm',
  182. '.xml',
  183. ]
  184. _ERROR_TEMPLATE_RE = re.compile(r'^\d{3}\.html?$')
  185. def is_error_template(path):
  186. """
  187. Return True if the given file path is an HTTP error template.
  188. """
  189. return bool(_ERROR_TEMPLATE_RE.match(path))
  190. def get_relative_url(url, other):
  191. """
  192. Return given url relative to other.
  193. """
  194. if other != '.':
  195. # Remove filename from other url if it has one.
  196. parts = posixpath.split(other)
  197. other = parts[0] if '.' in parts[1] else other
  198. relurl = posixpath.relpath(url, other)
  199. return relurl + '/' if url.endswith('/') else relurl
  200. def normalize_url(path, page=None, base=''):
  201. """ Return a URL relative to the given page or using the base. """
  202. path = path_to_url(path or '.')
  203. # Allow links to be fully qualified URL's
  204. parsed = urlparse(path)
  205. if parsed.scheme or parsed.netloc or path.startswith(('/', '#')):
  206. return path
  207. # We must be looking at a local path.
  208. if page is not None:
  209. return get_relative_url(path, page.url)
  210. else:
  211. return posixpath.join(base, path)
  212. def create_media_urls(path_list, page=None, base=''):
  213. """
  214. Return a list of URLs relative to the given page or using the base.
  215. """
  216. urls = []
  217. for path in path_list:
  218. urls.append(normalize_url(path, page, base))
  219. return urls
  220. def path_to_url(path):
  221. """Convert a system path to a URL."""
  222. return '/'.join(path.split('\\'))
  223. def get_theme_dir(name):
  224. """ Return the directory of an installed theme by name. """
  225. theme = get_themes()[name]
  226. return os.path.dirname(os.path.abspath(theme.load().__file__))
  227. def get_themes():
  228. """ Return a dict of all installed themes as (name, entry point) pairs. """
  229. themes = {}
  230. builtins = pkg_resources.get_entry_map(dist='mkdocs', group='mkdocs.themes')
  231. for theme in pkg_resources.iter_entry_points(group='mkdocs.themes'):
  232. if theme.name in builtins and theme.dist.key != 'mkdocs':
  233. raise exceptions.ConfigurationError(
  234. "The theme {} is a builtin theme but {} provides a theme "
  235. "with the same name".format(theme.name, theme.dist.key))
  236. elif theme.name in themes:
  237. multiple_packages = [themes[theme.name].dist.key, theme.dist.key]
  238. log.warning("The theme %s is provided by the Python packages "
  239. "'%s'. The one in %s will be used.",
  240. theme.name, ','.join(multiple_packages), theme.dist.key)
  241. themes[theme.name] = theme
  242. return themes
  243. def get_theme_names():
  244. """Return a list of all installed themes by name."""
  245. return get_themes().keys()
  246. def dirname_to_title(dirname):
  247. """ Return a page tile obtained from a directory name. """
  248. title = dirname
  249. title = title.replace('-', ' ').replace('_', ' ')
  250. # Capitalize if the dirname was all lowercase, otherwise leave it as-is.
  251. if title.lower() == title:
  252. title = title.capitalize()
  253. return title
  254. def get_markdown_title(markdown_src):
  255. """
  256. Get the title of a Markdown document. The title in this case is considered
  257. to be a H1 that occurs before any other content in the document.
  258. The procedure is then to iterate through the lines, stopping at the first
  259. non-whitespace content. If it is a title, return that, otherwise return
  260. None.
  261. """
  262. lines = markdown_src.replace('\r\n', '\n').replace('\r', '\n').split('\n')
  263. while lines:
  264. line = lines.pop(0).strip()
  265. if not line.strip():
  266. continue
  267. if not line.startswith('# '):
  268. return
  269. return line.lstrip('# ')
  270. def find_or_create_node(branch, key):
  271. """
  272. Given a list, look for dictionary with a key matching key and return it's
  273. value. If it doesn't exist, create it with the value of an empty list and
  274. return that.
  275. """
  276. for node in branch:
  277. if not isinstance(node, dict):
  278. continue
  279. if key in node:
  280. return node[key]
  281. new_branch = []
  282. node = {key: new_branch}
  283. branch.append(node)
  284. return new_branch
  285. def nest_paths(paths):
  286. """
  287. Given a list of paths, convert them into a nested structure that will match
  288. the pages config.
  289. """
  290. nested = []
  291. for path in paths:
  292. if os.path.sep not in path:
  293. nested.append(path)
  294. continue
  295. directory, _ = os.path.split(path)
  296. parts = directory.split(os.path.sep)
  297. branch = nested
  298. for part in parts:
  299. part = dirname_to_title(part)
  300. branch = find_or_create_node(branch, part)
  301. branch.append(path)
  302. return nested
  303. class WarningFilter(logging.Filter):
  304. """ Counts all WARNING level log messages. """
  305. count = 0
  306. def filter(self, record):
  307. if record.levelno == logging.WARNING:
  308. self.count += 1
  309. return True
  310. # A global instance to use throughout package
  311. warning_filter = WarningFilter()