cloudflare/ClickHouse
Publicmirrored fromhttps://github.com/cloudflare/ClickHouse
docs/tools/mdx_clickhouse.py
66lines · modecode
7 years ago
| 1 | #!/usr/bin/env python |
| 2 | # -*- coding: utf-8 -*- |
| 3 | from __future__ import unicode_literals |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | import markdown.inlinepatterns |
| 8 | import markdown.extensions |
| 9 | import markdown.util |
| 10 | |
| 11 | import slugify as slugify_impl |
| 12 | |
| 13 | class ClickHouseLinkMixin(object): |
| 14 | |
| 15 | def handleMatch(self, m): |
| 16 | single_page = (os.environ.get('SINGLE_PAGE') == '1') |
| 17 | try: |
| 18 | el = super(ClickHouseLinkMixin, self).handleMatch(m) |
| 19 | except IndexError: |
| 20 | return |
| 21 | |
| 22 | if el is not None: |
| 23 | href = el.get('href') or '' |
| 24 | is_external = href.startswith('http:') or href.startswith('https:') |
| 25 | if is_external: |
| 26 | if not href.startswith('https://clickhouse.yandex'): |
| 27 | el.set('rel', 'external nofollow') |
| 28 | elif single_page: |
| 29 | if '#' in href: |
| 30 | el.set('href', '#' + href.split('#', 1)[1]) |
| 31 | else: |
| 32 | el.set('href', '#' + href.replace('/index.md', '/').replace('.md', '/')) |
| 33 | return el |
| 34 | |
| 35 | |
| 36 | class ClickHouseAutolinkPattern(ClickHouseLinkMixin, markdown.inlinepatterns.AutolinkPattern): |
| 37 | pass |
| 38 | |
| 39 | |
| 40 | class ClickHouseLinkPattern(ClickHouseLinkMixin, markdown.inlinepatterns.LinkPattern): |
| 41 | pass |
| 42 | |
| 43 | |
| 44 | class ClickHousePreprocessor(markdown.util.Processor): |
| 45 | def run(self, lines): |
| 46 | if os.getenv('QLOUD_TOKEN'): |
| 47 | for line in lines: |
| 48 | if '<!--hide-->' not in line: |
| 49 | yield line |
| 50 | else: |
| 51 | for line in lines: |
| 52 | yield line |
| 53 | |
| 54 | |
| 55 | class ClickHouseMarkdown(markdown.extensions.Extension): |
| 56 | |
| 57 | def extendMarkdown(self, md, md_globals): |
| 58 | md.preprocessors['clickhouse'] = ClickHousePreprocessor() |
| 59 | md.inlinePatterns['link'] = ClickHouseLinkPattern(markdown.inlinepatterns.LINK_RE, md) |
| 60 | md.inlinePatterns['autolink'] = ClickHouseAutolinkPattern(markdown.inlinepatterns.AUTOLINK_RE, md) |
| 61 | |
| 62 | def makeExtension(**kwargs): |
| 63 | return ClickHouseMarkdown(**kwargs) |
| 64 | |
| 65 | def slugify(value, separator): |
| 66 | return slugify_impl.slugify(value, separator=separator, word_boundary=True, save_order=True) |