~nskaggs/help-app/functional-test-template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import codecs
import os
import sys
import tempfile


def require(package):
    print('Missing prerequisites. Please run: '
          '"sudo apt install %s"' % package)
    sys.exit(1)

try:
    import magic
except:
    require('python3-magic')

try:
    import markdown
except:
    require('python3-markdown')

from pelicanconf import (
    MD_EXTENSIONS,
    TOP_LEVEL_DIR,
)

BCP47_OVERRIDES = (
    ('zh_CN', 'zh-hans'),
    ('zh_TW', 'zh-hant'),
)

MD_MAGIC_FILE_TYPES = [
    'ASCII text',
    'UTF-8 Unicode text',
    'UTF-8 Unicode text, with very long lines',
]


def normalise_path(path):
    return os.path.relpath(path, TOP_LEVEL_DIR)


def full_path(path):
    return os.path.abspath(os.path.join(TOP_LEVEL_DIR, path))


def use_top_level_dir():
    pwd = os.getcwd()
    os.chdir(TOP_LEVEL_DIR)
    return pwd


def _temp_write_markdown(fn):
    (ret, tmp) = tempfile.mkstemp()
    length = 0
    ret = True
    try:
        markdown.markdownFromFile(fn, extensions=MD_EXTENSIONS, output=tmp)
    except:
        print('Could not convert "%s" into Markdown.' % fn)
        ret = False
    if ret:
        length = len(codecs.open(tmp, 'r', 'utf-8').read())
    os.remove(tmp)
    return (ret, length)


def verify_markdown_file(fn):
    ms = magic.open(magic.MAGIC_NONE)
    ms.load()
    fn = full_path(fn)
    if ms.file(fn) not in MD_MAGIC_FILE_TYPES:
        return False
    (ret, length) = _temp_write_markdown(fn)
    if not length:
        return False
    return ret


def find_bcp47_code(gettext_code):
    if gettext_code not in [c[0] for c in BCP47_OVERRIDES]:
        return gettext_code.lower().replace('_', '-')
    return [c[1] for c in BCP47_OVERRIDES
            if c[0] == gettext_code][0]